Search code examples
c++classusing

Define members of a class using class's namespace in c++


I have few classes with long names as well as their member functions. In C++ there is a trick which allows you to use one namespace and declare function:

namespace_name::foo();

and define it like this:

namespace namespace_name{
    foo() {}
}

For clarity of the code I'm wondering if there is a similar way to substitute definitions of functions:

LongClassName::LongFunctionName() {}

I'm sorry if I used improper vocabulary, but had no idea how to describe the problem.


Solution

  • In C++ there is a trick which allows you to use one namespace and turn

    This "trick" allows you to call function without specifying full function name with namespace. For function definition that does not work neither for namespace nor class. For namespace level function you either have to put that function definition inside namespace or mention it explicitly:

     namespace foo {
         void bar(); // foo::bar() declared
     }
    
     // you can define it as this
     namespace foo {
         void bar() {}
    }
    
    // or this
    void foo::bar() {}
    
    // this does not work
    using namespace foo;
    void bar() {} // ::bar() is defined here not foo::bar()
    

    for class method definition - class name must be always used (and possibly namespace as well if any) unless you define them inside class itself (and declare them inline implicitly):

    class VeryLongName {
    public:
        void method1() {}
        void method2() {}
    };