Site icon T4Tutorials.com

Composition In Class Diagram with Examples

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

  1. Every motorcycle has tires
  2. Every university has different departments.
  3. Every house has rooms.
  4.  A car has a battery.
  5. The sports club has Cricket playgrounds.
  6. The school has a canteen.
  7. Human has heart.

When we can use composition?

we can use composition in cases where one object “has” (or is part of) another object.

Exit mobile version