Composition In Class Diagram with Examples.
#include <iostream> using namespace std; class Animal { public: void eat() { cout << "I can eat!" << endl; } void sleep() { cout << "I can sleep!" << endl; } }; class Dog { public: Animal x; }; int main() { // Create object of the Dog class Dog dog1; // Calling members of the base class dog1.x.eat(); return 0; }
Examples of Composition
- Every motorcycle has tires
- Every university has different departments.
- Every house has rooms.
- A car has a battery.
- The sports club has Cricket playgrounds.
- The school has a canteen.
- Human has heart.
When we can use composition?
we can use composition in cases where one object “has” (or is part of) another object.