Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: "Class namespaces"? [duplicate]

If in C++ I have a class longUnderstandableName. For that class I have a header file containing its method declaration. In the source file for the class, I have to write longUnderstandableName::MethodA, longUnderstandableName::MethodB and so on, everywhere.

Can I somehow make use of namespaces or something else so I can just write MethodA and MethodB, in the class source file, and only there?

like image 851
Eve Avatar asked Oct 31 '10 22:10

Eve


2 Answers

typedef longUnderstandableName sn;

Then you can define the methods as

void sn::MethodA() {}
void sn::MethodB() {}

and use them as

sn::MethodA();
sn::MethodB();

This only works if longUnderstandableName is the name of a class. It works even if the class is deeply embedded in some other namespace.

If longUnderstandableName is the name of a namespace, then in the namespace (or source file) where you want to use the methods, you can write

using namespace longUnderstandableName;

and then call methods like

MethodA();
MethodB();

You should be careful not to use a using namespace foo; in header files, because then it pollutes every .cpp file that we #include the header file into, however using a using namespace foo; at the top of a .cpp file is definitely allowed and encouraged.

like image 143
Ken Bloom Avatar answered Nov 03 '22 13:11

Ken Bloom


Inside the methods of the classes, you can use the name without qualification, anyway: just drop the longUnderstandableName:: prefix.

In functions inside the class source file that are not methods, I suggest to introduce file-scope static inline functions, like so:

inline type MethodA(type param){
    return longUnderstandableName::MethodA(param);
}

Then you can call MethodA unqualified; due to the inline nature, this likely won't cost any runtime overhead.

like image 44
Martin v. Löwis Avatar answered Nov 03 '22 11:11

Martin v. Löwis