SecretIndividual
SecretIndividual

Reputation: 2529

How to inherit namespaces in c++

I have a few classes in my project that I would like to wrap into a namespace. I am using inheritance to make some child classes inherit properties from the parent.

I am wondering what the correct way is to define a namespace for the child classes. I tried declaring my parent class as:

namespace myNamespace {
    class A {
        ... 
    };
}

And then in the child class:

class B : public A {
    ...
};

However this does not seem to put class B in the same namespace as A (myNamespace ).

Upvotes: 2

Views: 685

Answers (2)

Yksisarvinen
Yksisarvinen

Reputation: 22304

There is not smart trick to do that. Namespaces are completely unrelated to classes or inheritance concept.

You should declare B in namespace as usual:

namespace myNamespace {
    class B : public A {
    ...
    };
}

Or put B definiton in the same block as A (if they are defined in the same file)

namespace myNamespace {
    class A {
        ... 
    };

    class B : public A {
        ...
    };
}

Upvotes: 4

Davide Spataro
Davide Spataro

Reputation: 7482

You cannot inherith namespace. There is not such a feature in C++.

What you can and should do is simply wrap your child class definition in the same namespace of your parent class as in the following:

namespace myNamespace { //same namespace of A
    class B : public A {

    };
}

Upvotes: 1

Related Questions