C++ Tutorial

Define C++

C++ First Program

Difference C and C++

C++ Operators

C++ Type Casting

C++ Function Overloading

C++ Default Arguments

C++ Inline Function

Define OOP's

C++ Keywords

C++ Classes

Exercise Classes

C++ Nested Classes

C++ Constructors

Exercise Constructor

C++ Friend function

C++ Operator Overloading

Ex: Operator Overloading

C++ Inheritance

C++ this pointer

C++ Polymorphism

Virtual Class & Function

C++ File Handling

Exercise File Handling

C++ Templates

C++ Exception Handling

C++ Graphics

Exercise Graphics

Page Stats

Visitor: 438

C++ Nested Classes

A nested class is a class that is declared inside another class. The nested class is also a member variable of the enclosing class and has the same access rights as the other members.

Example 1: Nested class

#include<iostream.h>
using namespace std;
class A
{
   public :
      void msg1()
      {
         cout<<"class A"<<endl;
      }
      class B
      {
         public :
            void msg2()
            {
               cout<<"class B"<<endl;
            }
      };
};
int main()
{
    A obj;
    obj.msg1();
    A::B obj2;
    obj2.msg2();
	return 0;
}

Example 2: Nested class

#include<iostream.h>
using namespace std;
class A
{
  int a;
  public:
    void input1()
    {
      cout<<"Class A";
    }
};

class B
{
  int b;
  public:
    A obj1;
    void input2()
    {
      cout<<"Class B";
    }
};

int main()
{
  B obj2;
  obj2.input2();
  obj2.obj1.input1();
  return 0;
}