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;
}
Related
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.
Could somebody tell me what is the difference between
using namespace android;
....
and
namespace android {
....
}
I found that almost all .cpp files in Android source code use the second one.
Also, If I want to include some files that use the type of second one in my own project, do I need to use namespace android{...} too?
Because if I do not, compiler would report error when I call methods of included files. Or do I need to add any prefix before method call?
namespace android {
extern int i; // declare here but define somewhere
void foo ();
}
-- is used for scoping variables and functions inside a particular name. While using/calling those variables/functions, use scope resolution operator ::. e.g.
int main ()
{
android::foo();
}
There is no restriction for putting all namespace declarations in a single body instance. Multiple namespace android bodies spread across several files, is possible and also recommended sometimes. e.g.
// x.cpp
namespace android {
void somefunc_1 ();
}
// y.cpp
namespace android {
void somefunc_2 ();
}
Now, sometimes you may find using :: operator inconvenient if used frequently, which makes the names unnecessarily longer. At that time using namespace directive can be used.
This using directive can be used in function scope / namespace scope / global scope; But not allowed in class scope: Why "using namespace X;" is not allowed inside class/struct level?).
int main ()
{
using namespace android;
foo(); // ok
}
void bar ()
{
foo(); // error! 'foo' is not visible; must access as 'android::foo()'
}
BTW, Had using namespace android; declared globally (i.e. above main()), then foo() can be accessed without :: in Bar() also.
My answer is probably only helpful if you are more experienced with Java. I'm guessing since you are doing android stuff that this is the case.
The following means that you are declaring a class called MyClass in the namespace android. The qualified name of the class would be android::MyClass.
namespace android {
class MyClass {...};
}
It can be thought of similarly to the Java code:
package android;
public class MyClass {...}
The following means that you can use classes, functions etc. defined in the android namespace without having to use their qualified name (assuming they have been included).
using namespace android;
This
#include <path/to/MyClass.h>
using namespace android;
can be thought of similarly to the Java code:
import android.MyClass;
Say I have two different cpp files. Both declare classes with the same name, but perhaps a totally different structure (or perhaps the same structure, different implementation). The classes do not appear in the header files. (As an example, suppose they are Node classes for different list classes.)
I've seen these classes conflict. Is this expected by the standard? What solutions are there to this problem?
UPDATE:
As suggested by answers/comments, anonymous namespaces are what I was looking for.
The standard way around this problem is to wrap the classes in different namespaces.
It violates One Definition Rule. It's hard for compiler to detect the error, because they are in different compilation units. And even linker cannot detect all errors.
See an example in http://www.cplusplus.com/forum/general/32010/ . My compiler and linker (g++ 4.2.1) can build the final executable without any error, but the output is wrong.
If I change the example a bit, I get segmentation fault.
// main.cpp
#include <iostream>
#include <list>
using namespace std;
struct Handler
{
Handler() : d(10, 1.234) {}
list<double> d;
};
extern void test_func();
int main(void)
{
Handler h;
cout << h.d.back() << endl;
test_func();
return 0;
}
// test.cpp
#include <iostream>
#include <string>
using namespace std;
struct Handler
{
Handler() : d("test Handler") {}
string d;
};
void test_func()
{
Handler h;
cout << h.d << endl;
}
It's recommended to differentiate you class by namespace. For example of Node, you can use nest class and define the Node in the parent list class. Or you can add you class in anonymous namespace. See How can a type that is used only in one compilation unit, violate the One Definition Rule?
I'm not sure if I'm missing some detail here, but you wrap each class in a namespace.
namespace A {
class Node { };
}
namespace B {
class Node { };
}
Then you can use A::Node or B::Node.
You can use namespace to have multiple classes with same name by sub-scoping them in different namespaces. See: http://www.cplusplus.com/doc/tutorial/namespaces/
I've seen these classes conflict. Is this expected by the standard?
The standard says you can't do that. It would violate the one definition rule. (How to fix this has already been covered in other answers)
id.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
static int a;
};
int A::a=20;
class b
{
public:
b()
{
cout<<A::a<<endl;
}
};
int main()
{
b *b1 = new b();
return 0;
}
id1.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class c
{
public:
int get()
{
cout<<A::a<<endl;
}
};
int main()
{
c c1;
c1.get();
return 0;
}
This is the way they have declared and got the output in one program but when I'm trying it I'm getting errors as the class is not a namespace or the program id is not included in the id1 file... How to get the variable that is stored in one file into the other file without using namespace and including the header file is there any option for it?
Two separate programs as shown (they're separate because they both define main()) cannot share variables in any simple way.
If the two separate files were to be integrated into a single program, so one of the main() programs was replaced, then you would fall back on the standard techniques of declaring the variable A::a in a header and using that header in both modules. The header would also define class A. This is the only sane way to do it.
You could write the definition of the class twice, once in each file, and declare the variable as an extern in one file and define it in the other, but that is not particularly sensible even in this simple case and rapidly degenerates into unmaintainable disaster if the code gets any more complex and there are more shared variables.
Of course, you might want to consider not using a global variable at all, but provide instead an accessor function. However, you still end up with a header declaring the services provided by the class A and the code implementing those services, and the code consuming those services.
In a header I have a setup like this
namespace NS {
typedef enum { GOOD, BAD, UGLY }enum_thing;
class Thing {
void thing(enum_thing elem);
}
}
and of course another cpp file that goes along with that header. Then I have a thread cpp file that contains main(). In this cpp file I use that enum to pass to the method thing().
using namespace NS;
int main() {
Thing t();
t.thing(BAD);
}
and of course I get other errors from G++ saying BAD was not declared. Any help on how I could overcome this error?
After correcting numerous little syntax errors in the sample code, it compiles just fine for me. Check that you've spelled the names correctly. Can you access the enum as NS::BAD? Perhaps you haven't included the correct header? Make sure you have
#include "FileWithEnum.h" at the top.
namespace NS {
typedef enum { GOOD, BAD, UGLY }enum_thing;
class Thing {
public:
void thing(enum_thing elem){}
};
}
using namespace NS;
int main() {
Thing t;
t.thing(BAD);
return 0;
}
Test it yourself:
http://codepad.org/Uw0XjOlF
Can you avoid using a typedef? Just do:
enum Foobar {good, bad, hello};
It should work. It does for me (the variant by Mystagogue should also work). I understand you had some other error messages ?
You probably just have to fix the header to be syntaxically correct, like putting a semi-colon at the end of class Thing, etc. When the header will be OK, the message about BAD not in namespace should also disappear.