Coders Packet

Nested Class in C++

By Akansh Upadhyay

In this guide we will talk about concept of nested class, it's advantages and implementation of nested class.

What is Nested Class?

A nested class is a class that is declared inside an enclosing class(i.e. declared in the scope of the enclosing class).

It is treated as a member variable of the enclosing class and has the same access rights as other members. 

Also, the member functions of the enclosing class do not have any special access to the member functions of the nested class.

Advantages of Nested Class:

It has the ability to access member functions and data members of the main class including private.

It increases encapsulation.

It reduces code and logically groups classes in one place.

Syntax:

Syntax Nested Class

Program to understand Nested Class:

#include
using namespace std;
class Out{
  public:
    class In{
      private:
        int a,b,c,d;
      public:
        void add(int x,int y)
        {
          a=x+y;
          cout<<"\nThe addition of number is "<<a;
        }
        void sub(int x,int y)
        {
          b=x-y;
          cout<<"\nThe subtraction of number is "<<b;
        }
        void mul(int x,int y)
        {
          c=x*y;
          cout<<"\nThe multiplication of number is "<<c;
        }
        void div(int x,int y)
        {
          d=x/y;
          cout<<"\nThe division of number is "<<d;
        }
    };
};
int main()
{
  Out::In obj;
  obj.add(23,12);
  obj.sub(30,3);
  obj.mul(25,2);
  obj.div(12,4);
  
}

Output:

Nested class output

Download Complete Code

Comments

No comments yet