Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Association, Aggregation and Composition

User image

Published by

sanya sanya

Published at: 6th Aug, 2023
2.025 mins read

Association, Aggregation, and Composition are three types of relationships between classes in Object-Oriented Programming (OOP). These relationships define how classes are connected and how they interact with each other.

1. Association:

Association represents a "using" or "has-a" relationship between classes, where one class is related to another class but does not own or have exclusive ownership of the associated class.

Association is typically represented using pointers or references. A class may have a member that is a pointer or reference to another class, indicating that the class uses or has access to the associated class.

Example:

class Book {

// Class definition for Book

};

class Library {

public:

// Member variable that represents an association with Book class

Book* book;

};

In this example, the ‘Library’ class is associated with the ‘Book’ class using a pointer ‘Book* book’. The ‘Library’ class uses or has access to the ‘Book’ class, but it doesn't own the ‘Book’ objects.

2. Aggregation:

Aggregation is a "whole-part" relationship between classes, where one class (the whole) contains or is composed of other classes (the parts). The parts can exist independently of the whole.

Aggregation is typically represented using pointers or references. A class contains member variables that are pointers or references to other classes, representing the "has-a" relationship.

Example:

class Engine {

// Class definition for Engine

};

class Car {

public:

// Member variable that represents aggregation with Engine class

Engine* engine;

};

In this example, the ‘Car’ class is composed of an ‘Engine’ class through a pointer ‘Engine* engine’. The ‘Car’ class is the whole, and the ‘Engine’ class is a part, but the ‘Engine’ can exist independently of the ‘Car’.

3. Composition:

Composition is a "whole-part" relationship similar to aggregation, but with stronger ownership semantics. In composition, the parts are created and destroyed together with the whole. If the whole is destroyed, all its parts are also destroyed.

Example:

class Wheel {

// Class definition for Wheel

};

class Car {

private:

// Member objects that represent composition with Wheel class

Wheel frontLeftWheel;

Wheel frontRightWheel;

Wheel rearLeftWheel;

Wheel rearRightWheel;

};

In this example, the ‘Car’ class is composed of four ‘Wheel’ objects, and these wheels are part of the ‘Car’ object. When a ‘Car’ object is created, its wheels are also created, and when the ‘Car’ object is destroyed, its wheels are also destroyed.

Library

WEB DEVELOPMENT

FAANG QUESTIONS