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 |
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:
1 2 3 4 5 6 7 8 | class ClassName { ... friend return–type function–name(params–list); ... }; |
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.