DEFINITION 5: COMPOSITION - PRATMG/2143-OOP-Tamang GitHub Wiki
In reality, complex objects are frequently constructed from smaller, simpler objects. A car, for example, is constructed from a metal frame, an engine, tires, a transmission, a steering wheel, and a variety of other components. A personal computer is made up of various components such as a CPU, a motherboard, memory, and so on. You, too, are made up of smaller parts: a head, a body, some legs, arms, and so on. Object composition refers to the process of constructing complex objects from simpler ones.
Object composition, in general, represents a "has-a" relationship between two objects. A vehicle "has" a transmission. Your computer "does" have a CPU. You have a "heart." The complex object is also known as the whole or the parent. The simpler object is frequently referred to as a part, child, or component.
An object and a part must have the following relationship to qualify as a composition:
- The part (member) is part of the object (class)
- The part (member) can only belong to one object (class) at a time
- The part (member) has its existence managed by the object (class)
- The part (member) does not know about the existence of the object (class)
class Fraction
{
private:
int m_numerator;
int m_denominator;
public:
Fraction(int numerator=0, int denominator=1)
: m_numerator{ numerator }, m_denominator{ denominator }
{
// We put reduce() in the constructor to ensure any fractions we make get reduced!
// Since all of the overloaded operators create new Fractions, we can guarantee this will get called here
reduce();
}
};
My reference: