Home CPP Interview Questions

Explain what is nested class

Nested Classes in C++:

A class defined within another class is a nested class.

Nested class' scope is within its enclosing class. Nested class name is not visible outside the enclosing class without qualifying it with enclosing class name. That is, enclosing_class_name::nested_class_name.

Example of nested classes in C++:

class Employee
{
public:
  class Data
  {

  public:
    int age;
    int unique_id;
    void display()
    { cout<<unique_id<< " " <<age; }

  };

  void printData( Data d)
  {
    d.unique_id=1;
    d.display();
  }
};

int  main()
{
  Employee emp;
  Employee::Data d;
  d.age=23;
  emp.printData(d);
}