Explain Composition in C++ with an example
October 28, 2007 · Filed Under C++ Questions, Placement Questions
![]() Don't want to miss a single bit? Subscribe By Email for Daily Jobs |
Composition allows software to be developed by assembling existing components rather than creating new ones. Composition is also sometimes called as aggregation and defines the process of putting an object inside another object. It models the has-a relationship. E.g. a class employee can contain an object of type salary which itself is another type of object. e.g.
class Salary
{
private:
double DA;
double HRA;
double travelAllowance;
double basic salary;
public:
//member functions
};
Class Employee
{
private:
int empno;
Salary salary; //composition: salary object is contained inside employee
public:
//member functions
};
Related Articles
- What are objects ? What is common between all objects of a class ?
- What are classes ? How are they defined ?
- What are static Data and Static Member Functions in C++ ?
- State all the class access modifiers and explain each one of them
- What are Virtual Functions ? Why do we need Virtual Functions? Explain with an example.


