Saturday 2 October 2010

NESTED CLASSES



NESTED CLASSES

A class can be defined inside another class. Such a class is known as a nested class. The class that contains the nested class is called as the enclosing class. Nested classes can be defined in the private, protected, public portions of the enclosing class.


class A    // class A is enclosing class
{
class B    // class B is nested class
{
   //definition of  class B
}

// definition of class A
}

The size of the objects of an enclosing class is not affected by the presence of the nested classes.

#include<iostream.h>
class A
{
int x;

public:
class B
{
int y;
};
};

void main()
{
cout<< sizeOf(A);
cout<<size Of (int);
}

Output:  // from the output it can be seen that the size of class A is not affected by the nested
                 class.
4
4

Creating the objects and Defining member functions of nested class:

Class A
{
Public:
Class B
{
Public:
void BTest();
}
};

Creating objects of nested class:

A::B   bObj;

Defining the member functions of nested class out the side the enclosing class:

A::B::BTest()
{
  // body of BTest

}
By default, the enclosing class, and the nested class do not have any access rights to each others private data members.

Member functions of the nested class can access the public members of the enclosing class only through an object, or a pointer or a reference  of the enclosing class.

Example:

Class A
{
Public:
Void ATest();
Class B
{
Public:
Void BTest (A&);
Void BTest1();
};
};

Void A::B::BTest(A& ARef)
{
ARef.ATest();  // No problem. B is accessing Class A’s member function through a reference of class A.
}

Void A::B::BTest1()
{
ATest()  // Error. Since ATest() belongs to class A.
}

No comments:

Post a Comment