What is object composition in C++ programming2 min read

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:

Friend Functions

A friend function is a non-member function which can access the private and protected members of a class. To declare an external function as a friend of the class, the function prototype preceded with friend keyword should be included in that class. Syntax for creating a friend function is as follows:

Following are the properties of a friend function:

  • Friend function is a normal external function which is given special access to the private and protected members of a class.
  • Friend functions cannot be called using the dot operator or -> operator.
  • Friend function cannot be considered as a member function.
  • A function can be declared as friend in any number of classes.
  • As friend functions are non-member functions, we cannot use this pointer with them.
  • The keyword friend is used only in the declaration. Not in the definition.
  • Friend function can access the members of a class using an object of that class.

Take your time to comment on this article.

Leave a Comment