C++

How to implement nested classes in C++2 min read

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:




Output for the above program is as follows:

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:

Output for the above program is as follows:

Take your time to comment on this article.

Leave a Comment