Nested Classes in C++
1. Class inside a class is called nested class.
2. Nested classes are declared inside another enclosing class.
3. A nested class is a member of class and it follows the same access rights that are followed by different members of class.
4. The members of an enclosing class have no other special access to members of nested class. The normal access rules shall be carried out.
5. If nested class is declared after public access specifiers inside the enclosing class then you must add scope resolution (::) during creating its object inside main function.
Example 1: nested class in c++
#include<iostream> using namespace std; class A{ public: //declaring nested class class B{ private: int num; public: void setData(int n1){ num = n1; } void showData(){ cout << "The number is: " << num; } }; }; int main(){ A :: B obj1; // :: used to create object of nested class obj1.setData(51); obj1.showData(); return 0; } /* OUTPUT The number is: 51 */
Example 2: nested class in c++
#include<iostream> #include<string.h> using namespace std; class Student{ private: int roll_no; char name[35]; //nested class class Address{ private: int house_no; char street[35]; char city[30]; char state[30]; char pincode[7]; public: void setAddress(int h, char *s, char *c, char *st, char *p){ house_no = h; strcpy(street, s); strcpy(city, c); strcpy(state, st); strcpy(pincode, p); } void showAddress(){ cout << "\n" << house_no << endl; cout << street << " " << city; cout << " " << pincode << endl; cout << state; } }; Address add; public: void setRollNo(int roll){ roll_no = roll; } void setName(char *n){ strcpy(name, n); } void setAddress(int h, char *s, char *c, char *st, char *p){ add.setAddress(h,s,c,st,p); } void showStudentData(){ cout << "STUDENT DATA: " << endl; cout << name << " "; cout << roll_no << " "; add.showAddress(); } }; int main(){ Student S1; S1.setRollNo(101); S1.setName("Ram Dayal Sharma"); S1.setAddress(252, "Railway Colony", "Samastipur", "848101", "Bihar"); S1.showStudentData(); return 0; }