Coupon Accepted Successfully!


Qualifier and Nested Classes

The class declaration can also be done inside the other class. While declaring object of such class, it is necessary to precede the name of the outer class. The name of outer class is called qualifier name, and the class defined inside is called nested class.

The use of nested classes enhances the power of abstract data type and helps to construct more powerful data structure. The qualifier (host class) and the nested class follow the same access conditions. The nested classes are useful to hide a particular class and its objects within a qualifier class. The following program illustrates this.


9.17 Write a program to declare classes within classes and access the variables of both the classes.

Explanation: In the above program, class B is declared inside class A. All the members of both the classes are declared public so that they can be easily accessed. Both the classes have constructors to initialize the member variables. The class B also has one member function show() to display the contents on the screen.

In function main(), A::B b declares object of class B. The name of class A is preceded because the class B is inside the class A. If we declare an object using the statement B b, the program will be executed with a warning message “Use qualified name to access nested type ‘A::B’”. Here, the class A acts as a qualified class.

The show() function is a member of class B. Due to this, variable y is its member variable and can be directly accessed. To access the variable of a qualified class A, object of class A a is declared and through this object variable x is accessed. The data variables are public. In case of private, we can access member variables using member functions. There is no limit for declaring classes within classes. The following program explains this.

9.18 Write a program to declare multiple qualifier classes and declare an object of every class.

Explanation: In the above program, classes A, B, and C are declared. The class B is declared inside the class A. The class C is declared inside the class B. The classes A and B are qualified classes for class C. The class A is qualified class for class B. Each class has a constructor that initializes and displays the contents of the object.

Test Your Skills Now!
Take a Quiz now
Reviewer Name