C++ allows programmers to declare one class inside another class. Such classes are called nested classes. When a class B is declared inside class A, class B cannot access the members of class A. But class A can access the members of class B through an object of class B. Following are the properties of a nested class:
- A nested class is declared inside another class.
- The scope of inner class is restricted by the outer class.
- While declaring an object of inner class, the name of the inner class must be preceded by the outer class name and scope resolution operator.
Following program demonstrates the use of nested classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include<iostream> using namespace std; class Student { private: string regdno; string branch; int age; public: class Name { private: string fname; string mname; string lname; public: string get_name() { return fname + " " + mname + " " + lname; } void set_name(string f, string m, string l) { fname = f; mname = m; lname = l; } }; }; int main() { Student::Name n; n.set_name("L", "H", "CODINGSEC"); cout << "Name is: " << n.get_name(); return 0; } |
Output for the above program is as follows:
1 2 3 | Name is: L H CODINGSEC |
Object Composition
In real-world programs an object is made up of several parts. For example a car is made up of several parts (objects) like engine, wheel, door etc. This kind of whole part relationship is known as composition which is also known as has-a relationship. Composition allows us to create separate class for each task. Following are the advantages or benefits of composition:
- Each class can be simple and straightforward.
- A class can focus on performing one specific task.
- Classes will be easier to write, debug, understand, and usable by other people.
- Lowers the overall complexity of the whole object.
- The complex class can delegate the control to smaller classes when needed.
Following program demonstrates composition:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include<iostream> using namespace std; class Engine { public: int power; }; class Car { public: Engine e; string company; string color; void show_details() { cout << "Compnay is: " << company << endl; cout << "Color is: " << color << endl; cout << "Engine horse power is: " << e.power; } }; int main() { Car c; c.e.power = 500; c.company = "hyundai"; c.color = "black"; c.show_details(); return 0; } |
Output for the above program is as follows:
1 2 3 4 5 | Compnay is: hyundai Color is: black Engine horse power is: 500 |
Take your time to comment on this article.