7

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

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
Umut Tabak
  • 1,862
  • 4
  • 26
  • 41

3 Answers3

12

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.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
8

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.

Community
  • 1
  • 1
James McNellis
  • 348,265
  • 75
  • 913
  • 977
3

You dont need to denote NS since you are already inside it

namespace NS
{
    class D: public B{ //is fine
    };
}

Something else you might find interesting later is :

#include <iostream>
int x = 10;

int main()
{
    int x = 5;
    //This will show the local x
    std::cout << x << std::endl;
    //This is how you access the Global x
    std::cout << ::x << std::endl;

    return 0;
}