Nested Classes in C++


A nested class is a class that is declared in another class. The nested class is also a member variable of the enclosing class and has the same access rights as the other members. However, the member functions of the enclosing class have no special access to the members of a nested class.

A program that demonstrates nested classes in C++ is as follows.

Example

 Live Demo

#include<iostream>
using namespace std;
class A {
   public:
   class B {
      private:
      int num;
      public:
      void getdata(int n) {
         num = n;
      }
      void putdata() {
         cout<<"The number is "<<num;
      }
   };
};
int main() {
   cout<<"Nested classes in C++"<< endl;
   A :: B obj;
   obj.getdata(9);
   obj.putdata();
   return 0;
}

Output

Nested classes in C++
The number is 9

In the above program, class B is defined inside the class A so it is a nested class. The class B contains a private variable num and two public functions getdata() and putdata(). The function getdata() takes the data and the function putdata() displays the data. This is given as follows.

class A {
   public:
   class B {
      private:
      int num;
      public:
      void getdata(int n) {
         num = n;
      }
      void putdata() {
         cout<<"The number is "<<num;
      }
   };
};

In the function main(), an object of the class A and class B is defined. Then the functions getdata() and putdata() are called using the variable obj. This is shown below.

cout<<"Nested classes in C++"<< endl;
A :: B obj;
obj.getdata(9);
obj.putdata();

Updated on: 24-Jun-2020

21K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements