on Leave a Comment

C++ Nested Classes

A class declared inside a class is called nested class. A nested class can be declared under any access modifier like private, public and protected. A nested class is a member of an enclosing class and has all rights like other members. If a nested class is declared under private access modifier, then we can't access nested class outside of the enclosing class.

General Syntax of Nested Classes in C++

class A
{
Access Modifier:
    class B
    {
        ......
        ......

    Access Modifier:
        class C
        {
            ......
            ......
            ......
        };
    };
};

Example of Nested Classes in C++

#include<iostream>
#include<string.h>
using namespace std;

/*Enclosing class*/
class Student
{
private:
    int roll_no;
    char name[20];

    /*Nested class*/
    class Address
    {
    private:
        char country[20];
        char city[20];
    public:
        void setAddress(char *co, char *ci)
        {
            strcpy(country, co);
            strcpy(city, ci);
        }
        void showAddress()
        {
            cout<<"Address Details:";
            cout<<"\n  Country      : "<<country;
            cout<<"\n  City         : "<<city;
        }
    };
    Address A1;

public:
    void setRollno(int n)
    {
        roll_no = n;
    }
    void setName(char *n)
    {
        strcpy(name, n);
    }
    void setAddress(char *co, char *ci)
    {
        A1.setAddress(co, ci);
    }

    void showRollno()
    {
        cout<<"Roll Number    : "<<roll_no<<endl;
    }
    void showName()
    {
        cout<<"Name of Student: "<<name<<endl;
    }
    void showAddress()
    {
        A1.showAddress();
    }
};
int main()
{
    Student stud1;
    stud1.setRollno(10);
    stud1.setName("John");
    stud1.setAddress("Australia", "Sydney");

    stud1.showRollno();
    stud1.showName();
    stud1.showAddress();
    return 0;
}

OUTPUT:

Roll Number    : 10
Name of Student: John
Address Details:
  Country      : Australia
  City         : Sydney

0 comments:

Post a Comment