Haiyuan Zhang
Haiyuan Zhang

Reputation: 42792

What's the scope of a type declaration within a class?

If a new type is declared whithin a class, like:

class foo {
public :
   struct s1 {
        int a ;
   };
private :
  struct s2 {
        int b ;
  };
};

then in what scope can the following statements be used:

s1 ss1;
s2 ss2;

Thanks in advance.

Upvotes: 3

Views: 476

Answers (4)

Narendra N
Narendra N

Reputation: 1270

The scope of the nested class is limited to the enclosing class. Those two classes cannot be accessed outside foo.

However there is a difference between the classes s1 & s2. You cannot create objects of s2 outside foo.

You would be able to create objects of s1 outside foo using a fully qualified name as in Foo:s1 fs1; The classes which inherit Foo, would be able to access s1, but not s2.

Upvotes: 1

There are two different questions there: where can I use the unqualified short name, and where I have access to each of the types.

You can use the unqualified name of an internal type whenever you are within the class scope. That would be inside the class declaration, and in the definition of the methods for the given class or derived classes that do not hide the names (there are some other specifics regarding dependent names in hierarchies involving templates, but that is probably outside of the scope of the question).

The second question is where you have access to the public vs. private members of a class. You can access the private members (including types) within the same class and in any class or function that is declared to be a friend of the class after the declaration of the class. Public members can be accessed from anywhere after the compiler has seen the declaration of the class.

Upvotes: 1

anon
anon

Reputation:

The type s1 can be used anywhere, but if used outside of foo's member functions, it must be qualified:

foo::s1 ss1;

The type s2 can only be used in member functions of foo.

Upvotes: 7

Péter Török
Péter Török

Reputation: 116266

As per your example, both can be used only inside class foo. With qualifier, however, s1 can also be used outside foo, like

foo::s1 ss1;

Upvotes: 1

Related Questions