Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inheritance and namespaces

Tags:

c++

namespaces

I am trying a my first useful object oriented program with some namespace usage. I have a base class B which is in the namespace NS. If I try to inherit from this base class to get the inheritance work, I should use the NS::B in the class decleration as below, is this really the case? Or is there a more widely accepted sytle for this inheritance syntax?

namespace NS
{
    class D: public NS::B{
    ...
    };
}

Best, Umut

like image 716
Umut Tabak Avatar asked Dec 01 '10 15:12

Umut Tabak


People also ask

Can namespaces be inherited?

Namespace inheritance applies to the namespaces/ directory of the hierarchical repository and all its subdirectories. Configs in other directories in the repository, such as cluster/ , are not subject to inheritance.

What namespace means?

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

Can we inherit namespace in C#?

If you are in namespace C, and you use using namespace A, you can use that class that derived from namespace B.

How do you inherit a class in another namespace?

If you think class A and class B should have under different namespaces (groups), kept them under different namespaces (groups). And when you need to access/ inherit one class from another, you just access/ inherit it following namespace standard.


2 Answers

If your D is in namespace NS, you don't have to qualify NS::B, since D and B are in the same namespace. You can just use class D : public B.

like image 190
Eli Bendersky Avatar answered Oct 24 '22 13:10

Eli Bendersky


When you are inside of namespace NS, you don't usually(1) need to qualify the names of functions, classes, or other entities that are in the namespace NS. Given:

namespace NS {
    class B { };
}

the following two definitions of D are the same:

namespace NS {
    class D : public NS::B { };
}

and:

namespace NS {
    class D : public B { };
}

(1) Argument-Dependent Lookup (ADL) can cause some ugly issues, especially when using templates, and to fix them you may need to qualify names.

like image 41
James McNellis Avatar answered Oct 24 '22 12:10

James McNellis