Nested Class Constructor in C++

In today’s tutorial, we will learn about nested class constructors in C++.

Let’s start with constructors first. What is a constructor? Constructors¬†are member functions of a class which initialize the values of objects of the class. They have the same name as the class name and they are automatically called when an object is created. Now, what is a nested class? C++ allows us to define a class within another class. A nested class is a class defined within another class. Further, the class in which it is defined is called the qualifier class.

Here’s an example to show the use of nested class constructors:

C++ Program for nested class constructors :

#include<iostream>
using namespace std;
class Q {			//qualifier class
public:
  int q;
  Q(int x) { q = x; }		//qualifier class parameterized constructor
  class N {			//nested class
  public:
    int n;
    N(int y) { n = y; }		//nested class parameterized constructor
    void display(Q o1)		//member func to display the data members
    {
      cout << "q = " << o1.q << endl;
      cout << "n = " << n << endl;
    }
  };
};
int main()
{
  int q1, n1;
  cout << "Enter the value of q and n ";
  cin >> q1>> n1;
  Q o1(q1);		//object of qualifier class
  Q::N o2(n1);	        //object of nested class
  o2.display(o1);
  return 0;
}

Output:

Enter the value of q and n 20
30
q = 20
n = 30

Explanation of this program

In this code, we have made a qualifier class Q with the nested class N. Both of them have their individual parameterized constructors. The user will input the values and they will store in variables q1 and n1. For instance, we have given the values 20 and 30 to q1 and n1 respectively. We then pass these values as arguments while creating an object of each class to initialize the objects. Then we use the display member function is to display the values of both the objects. This displays the value of q =20 and n =30. Here, the scope of the nested class is limited to the qualifier class.

Hope this was helpful. Enjoy coding!

Also, learn:

Classes and objects in CPP

Multiple inheritance in C++

Leave a Reply

Your email address will not be published. Required fields are marked *