Sabtu, Februari 17, 2024

Hubungan Komposisi OOP dalam C++

———

Oleh hh (Sabtu, Februari 17, 2024)

Apakah Hubungan Komposisi (Composition Relationship) Objek?
- In object-oriented programming (OOP), object composition refers to building complex objects by combining simpler ones.
- Imagine assembling a mobile phone: it consists of various components like a camera, battery, screen, and sensors. Each of these components is a simpler object.
- The process of creating a mobile phone by putting together these components is an example of object composition.

Bagaimana ia berfungsi?
- In C++, we create classes to define objects. A class can contain other objects as its members.
- Consider two classes:
$$A~and~B$$
- B is a complex class that uses objects of class A as its data members.
- This relationship is called composition.
Here’s a simple example:
#include <iostream>
using namespace std;

class A {
public:
    int x;
    A() { x = 0; }
    A(int a) {
        cout << "Constructor A (int a) is invoked" << endl;
        x = a;
    }
};

class B {
    int data;
    A objA; // Composition: B has an object of class A
public:
    B(int a) : objA(a) {
        data = a;
    }
    void display() {
        cout << "Data in object of class B = " << data << endl;
        cout << "Data in member object of class A in class B = " << objA.x;
    }
};

int main() {
    B objb(25);
    objb.display();
    return 0;
}
In this example:
  • B contains an object of class A (composition).
  • B has-a A object.
  • In UML, [  B ]

    -------[  A  ]
  • When we create an instance of B, it also creates an instance of A.
  • The data in objA is part of the whole object B.

Jenis Komposisi Objek
There are two basic subtypes:
  1. Composition:

  •  Part-whole relationship.
  • A part belongs to only one object at a time.
  • The part’s existence is managed by the whole object.
  • Example: A car’s engine is a composition.

  1. Aggregation:
  • Parts can belong to multiple objects simultaneously.
  • The whole object isn’t responsible for the parts’ existence.
  • Example: A library and its books (books can be borrowed by different readers).
Remember, composition models relationships where one object has-a relationship with another.

Tiada ulasan:

Catat Ulasan

Pengikut langganan