OOPortal OOPortal

C++ Class Construct  «Prev  Next»
Lesson 7 Nested classes
Objective Examine some examples of nested classes.

Building Nested Classes in C++

Classes can be nested. Nested classes, like nested blocks, have inner and outer nomenclature. In C, nested structs were permitted, but the inner structs names were visible externally. Let us look at an example of nested classes:

char  c;      //external scope  ::c

class X {     //outer class declaration  X::
   class Y {  //inner class declaration  X::Y::
      void  foo(char e) { ::c = X::c = c = e; }
      char  c; //X::Y::c
   char  c; //X::c

In class Y, the member function foo(), when using ::c, references the global variable c. When foo() uses X::c, it references the outer class variable X::c. When using c, foo() references the inner class variable X::Y::c. The three variables named c are all accessible using the scope resolution operator. Furthermore, purely locally scoped classes can be created within blocks. Their definitions are unavailable outside their local block context.

void foo(){
  class local { ..... };
  local x;
  //other class and object declarations here       
local y;   //illegal local is scoped within foo()

Nesting function definitions

Notice that C++ allows you to nest function definitions by using class nesting. This is a restricted form of function nesting.
The member functions must be defined inside the local class, and cannot be referred to outside this scope.
As is the case in C, ordinary nested functions are not possible.