tags:

views:

122

answers:

5

the following code will help me illustate my question to you directly:

#include<iostream>

class foo {
  public:
  class bar {
    public:
      bar(int a) : m_a(a) {}
      void say() { std::cout << m_a << std::endl;}
    private:
      int m_a;
  };
};


int main()
{
  foo::bar b(3);
  b.say();
}

as you see, to declare a object of class bar, we use the quite namespace like syntax "foo::bar", although actually bar is just an embebed class type in class foo. my question is does the scope of a class itself is a namespace in c++?

+9  A: 

No, a class is not a namespace. A class does form a declarative region, though.

You use the same syntax (the :: operator) to refer to names declared at class scope as you do to refer to names declared at namespace scope.

James McNellis
+1 for recognizing the distinction.
JUST MY correct OPINION
+1  A: 

The scope of a class is not the same as the scope of a namespace. Classes can be templated, which affects the definitions in its scope. Classes can also have definitions that are only able to be used within that scope (private and protected).

Paul
A: 

The class name itself is not a namespace, although the scoping operator treats it as such, or almost as such anyways.

Vapen
+4  A: 

Another interesting distinction between classes and namespaces is that a namespace can be declared over multiple files and in multiple parts, but a class cannot. For example, you could do:

File a.hpp:
    namespace Foo {
        int memberA;
    }

File b.hpp:
    namespace Foo {
        int memberB;
    }
    ...
    namespace Foo {
        int memberC;
    }
antonm
+6  A: 

The class is not a namespace, it is a scope. You already used this term yourself. Namespace is a scope. Class is a scope as well. The :: operator is a scope resolution operator. Scope, not namespace, is the fundamental term that can act as a "common denominator" in this case. Scope is the reason why you can use the :: operator with both classes and namespaces on the left-hand side.

AndreyT