namespace n1 {
namespace n2 {
...
int myfunc(void)
{
return 1;
}
class myclass {
..
};
}
}
I thought it is possible to define a function this way, and access it both from 'myclass' and its derivatives. However gcc doesn't even want to compile this code:
multiple definition of `n1::n2::myfunc()'
This function is the only one here, what am I missing?
Thanks.
You need to either mark the function inline to avoid breaking the one definition rule, or place the implementation in a .cpp file, and leave only the declaration in the header.
Related
In one of my classes header file Lfo.h, I have a class definition where I put the member function definition out of the class (It might be better to have a separate .cpp file but it should be ok put here?):
// Lfo.h
class CLfo
{
public:
static int create (CLfo*& pCLfo);
};
int CLfo::create(CLfo *&pCLfo)
{
pCLfo = new CLfo;
return 0;
}
Then I have another class called CVibrato:
// Vibrato.h
class CVibrato
{
public:
static int create (CVibrato*& pCVibrato);
private:
CVibrato();
};
and the .cpp file (in the cpp file, I include Lfo.h because later on the vibrato class will have a lfo member but I haven't implemented right now):
// Vibrato.cpp
#include "Lfo.h"
#include "Vibrato.h"
int CVibrato::create(CVibrato *&pCVibrato)
{
pCVibrato = new CVibrato();
return 0;
}
CVibrato::CVibrato()
{
}
Then I want to create a instance of vibrato class in main()
#include "Vibrato.h"
#include "Lfo.h" // if comment this line out there will be no error, why is that?
int main()
{
CVibrato *vibrato = 0;
CVibrato::create(vibrato);
return 0;
}
However I get a 1 duplicate symbol for architecture x86_64 error. What is duplicated? It seems the reason is in Lfo.h, I put the definition of the member function outside of the class, if I put it inside, the program runs properly. But I cannot understand. In c++, aren't we allowed to do this? By the way, if one of my class (in my case vibrato) is going to have a class member of another class (in this case lfo), should I include the header file of member class in .h (vibrato.h) file or .cpp (vibrato.cpp) file?
Classes are declarations. No code is produced from a declaration. Even if you have a member function in the class, it is treated as if an inline by the compiler. Function bodies can be put in a header but should always be declared as inline. The compiler may not actually inline it, but it will treat it as a single instance for code creation.
Any time you:
void function( ) { }
Code is created for that function. If a header is included more than once the compiler is told to create the code more than once. But all functions must have unique names! So you get the duplicate error. That is why code generating lines belong in the .cpp files.
'inline' tells the compiler not to create immediate code but to create the code at the usage point.
You can't put class method definition directly in a header file, unless you explicitly mark it as inline. Like the following:
// Lfo.h
class CLfo
{
public:
inline static int create (CLfo*& pCLfo);
};
int CLfo::create(CLfo *&pCLfo)
{
pCLfo = new CLfo;
return 0;
}
Or,
// Lfo.h
class CLfo
{
public:
static int create (CLfo*& pCLfo);
};
inline int CLfo::create(CLfo *&pCLfo)
{
pCLfo = new CLfo;
return 0;
}
I'm writing utility functions for my current project.
Right now, I have a utility.h header which defines a class with static methods:
#pragma once
class Utils
{
public:
static int firstFunc()
{
return 0;
}
static bool secondFunc()
{
return false;
}
};
This header is included every time I need to use such functions (in two translation units at the moment) and it works just fine.
Now, after a code review, it was suggested to replace this class by C-style functions. My naive first attempt:
#pragma once
int firstFunc()
{
return 0;
}
bool secondFunc()
{
return false;
}
failed to link, returning a multiple definition of function error.
I understand why this happens: the header utils.h, which contains the function definitions, is present in two different compilation units: the linker doesn't know which definition to use.
I know that the solution is to move the definitions to a dedicated utils.cpp and leave only the declarations in the header.
My question now is: why didn't this happen when I had the class with static methods, when I still had multiple definitions of the same class in different translation units?
Functions definitions (static or not) that are written directly inside the class body are implicitly inline. Had you separated the definitions:
#pragma once
class Utils
{
public:
static int firstFunc();
static bool secondFunc();
};
static int Utils::firstFunc()
{
return 0;
}
static bool Utils::secondFunc()
{
return false;
}
... you'd have witnessed the exact same multiple definition error.
Also, these are not "C-style functions", just free (non-member) functions. C++ has nothing against free functions ;)
Is there any difference between wrapping both header and cpp file contents in a namespace or wrapping just the header contents and then doing using namespace in the cpp file?
By difference I mean any sort performance penalty or slightly different semantics that can cause problems or anything I need to be aware of.
Example:
// header
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
// cpp
namespace X
{
void Foo::TheFunc()
{
return;
}
}
VS
// header
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
// cpp
using namespace X;
{
void Foo::TheFunc()
{
return;
}
}
If there is no difference what is the preferred form and why?
The difference in "namespace X" to "using namespace X" is in the first one any new declarations will be under the name space while in the second one it won't.
In your example there are no new declaration - so no difference hence no preferred way.
Namespace is just a way to mangle function signature so that they will not conflict. Some prefer the first way and other prefer the second version. Both versions do not have any effect on compile time performance. Note that namespaces are just a compile time entity.
The only problem that arises with using namespace is when we have same nested namespace names (i.e) X::X::Foo. Doing that creates more confusion with or without using keyword.
There's no performance penalties, since the resulting could would be the same, but putting your Foo into namespace implicitly introduces ambiguity in case you have Foos in different namespaces. You can get your code fubar, indeed. I'd recommend avoiding using using for this purpose.
And you have a stray { after using namespace ;-)
If you're attempting to use variables from one to the other, then I'd recommend externalizing them, then initializing them in the source file like so:
// [.hh]
namespace example
{
extern int a, b, c;
}
// [.cc]
// Include your header, then init the vars:
namespace example
{
int a, b, c;
}
// Then in the function below, you can init them as what you want:
void reference
{
example::a = 0;
}
If the second one compiles as well, there should be no differences. Namespaces are processed in compile-time and should not affect the runtime actions.
But for design issues, second is horrible. Even if it compiles (not sure), it makes no sense at all.
The Foo::TheFunc() is not in the correct namespacein the VS-case. Use 'void X::Foo::TheFunc() {}' to implement the function in the correct namespace (X).
In case if you do wrap only the .h content you have to write using namespace ... in cpp file otherwise you every time working on the valid namespace. Normally you wrap both .cpp and .h files otherwise you are in risk to use objects from another namespace which may generate a lot of problems.
I think right thing to do here is to use namespace for scoping.
namespace catagory
{
enum status
{
none,
active,
paused
}
};
void func()
{
catagory::status status;
status = category::active;
}
Or you can do the following:
// asdf.h
namespace X
{
class Foo
{
public:
void TheFunc();
};
}
Then
// asdf.cpp
#include "asdf.h"
void X::Foo::TheFunc()
{
return;
}
I'm learning C++ now. What are the complete legal entities that can be put in a namespace?
Legal entities here means valid members of a namespace
Oh, this is a real question. I'm coming from .net and I have the .net mindset.
Any code can be put inside namespace.
However main() function must be at global namespace. It cannot be put inside user-defined namespace.
namespace userns
{
int main()
{
return 0;
}
}
This program wouldn't compile link : http://www.ideone.com/k6SPc
Its because userns::main() will not be considered entry-point of the program; it became just like any other user function, not the standard main(). To compile it successfull, you've to add main() at global namespace:
namespace userns
{
int main()
{
return 0;
}
}
int main()
{
return 0;
}
This will compile link now : http://www.ideone.com/76Ynu
Anything can be put in a namespace (which is legal for C++, of course).
Actually, everything is in some namespace - the global namespace, if not specified.
Everything can be put in namespace except few "entities", which will not compile.
(1) Globally overloaded operator new and operator delete
namespace N
{
void* operator new (size_t size) // error
{ ... }
}
(2) Definition of the constructs which are declared in outer scope of the namespace; for example you have a class A declared globally then you cannot define its method inside your namespace N. In the same way, if you have method declared in a namespace N then you cannot put its definition inside namespace N::Nested (i.e. Nested is a namespace inside N).
//file
struct A {
void foo ();
static int i;
};
namespace N
{
int A::i = 0; // error
void A::foo() // error
{}
}
Demo: this is not allowed.
I remember at least these 2 restrictions from my experience. Don't know about specs.
i have two questions that are fairly small and related so i will put them both in the same question.
i have been experimenting with classes and i was attempting to access a class in another file that wasn't in a class so for example.
//class 1 .cpp
void Class1::function1()//another error
{
function()
}
//main.cpp
void function()
{
//stuff happens
}
is there a way to-do this? or would i need to add this function to a class to get it to work. also how would you go about creating a function that receives a function as it parimetre? for example function(function2())
i am simply trying to access a function from a class as it would make my code easier to use later if the function that i am using doesn't get added to a class. with regards to the seconds question i which to create a function that receives a time and a function as an argument. it will wait for the specified time then execute the program
How to access a function in another file?
Depends on the type of function, there can be to cases:
1. Accessing class member functions in another file(Translation Unit):
Obviously, you need to include the header file, which has the class declaration in your caller translation unit.
Example code:
//MyClass.h
class MyClass
{
//Note that access specifier
public:
void doSomething()
{
//Do something meaningful here
}
};
#include"MyClass.h" //Include the header here
//Your another cpp file
int main()
{
MyClass obj;
obj.doSomething();
return 0;
}
2. Accessing free functions in another file(Translation Unit):
You do not need to include the function in any class, just include the header file which declares the function and then use it in your translation unit.
Example Code:
//YourInclude.h
inline void doSomething() //See why inline in #Ben Voight's comments
{
//Something that is interesting hopefully
}
//Your another file
#include"YourInclude.h"
int main()
{
doSomething()
return 0;
}
Another case as pointed out by #Ben in comments can be:
A declaration in the header file, followed by a definition in just one translation unit
Example Code:
//Yourinclude File
void doSomething(); //declares the function
//Your another file
include"Yourinclude"
void doSomething() //Defines the function
{
//Something interesting
}
int main()
{
doSomething();
return 0;
}
Alternately, a messy way to do this can be to just mark the function as extern in your another file and use the function.Not recommended but a possibility so here is how:
Example Code:
extern void doSomething();
int main()
{
doSomething();
return 0;
}
How would you go about creating a function that receives a function as it parameter?
By using function pointers
In a nutshell Function pointers are nothing but pointers but ones which hold address of functions.
Example Code:
int someFunction(int i)
{
//some functionality
}
int (*myfunc)(int) = &someFunction;
void doSomething(myfunc *ptr)
{
(*ptr)(10); //Calls the pointed function
}
You need a prototype for the function you want to call. A class body contains prototypes for all its member functions, but standalone functions can also have prototypes. Typically you organize these in a header file, included from both the file which contains the function implementation (so the compiler can check the signature) and in any files which wish to call the function.
(1) How can the `class` function be accessible ?
You need to declare the class body in a header file and #include that wherever needed. For example,
//class.h
class Class1 {
public: void function1 (); // define this function in class.cpp
};
Now #include this into main.cpp
#include"class.h"
You can use function1 inside main.cpp.
(2) How to pass a function of class as parameter to another function ?
You can use pointer to class member functions.