What is the purpose of Aggregation ( or Composition ) in C++ ?

This is a very famous question asked in C++ interviews especially, if you are an experienced professional.

Let me repeat the question “What is the purpose of Aggregation ( or Composition ) in C++ ?

Instead of building new software, Composition allows software to be developed by assembling existing components.

Aggregation, which is mostly known as composition, is the process of putting an object inside another object (the composite). It is known as has-a relationship. As a real world example, we can say, “Bathroom has a tub“, where, tub object is part of the bathroom object. As another example, a Hyundai i20 ( my car :) ) can be composed of, among other things, an Engine, Transmission, InstrumentPanel, and so on. In other words, a Hyundai i20 has an Engine.

Let us write it programmatically:

class Engine

{

public:

virtual void start( );

};

void Engine :: start( )

{

cout << “Engine Starting\n” ;

}

class HyundaiI20

{

public:

virtual void start( );

protected:

Engine eng; // An engine is a part of a HyundaiI20

};

void HyundaiI20 :: start( )

{

cout << “Starting Hyundai I20 \n”;

eng.start( );

}

int main( )

{

HyundaiI20 hi20;

hi20.start( );

}

It is common mistake among developers who has just got into the object oriented world to incorrectly use inheritance (is – a relationship) when they should use composition. For example, they might make HyundaiI20 inherit from Engine , which confused “is-a” with “has-a” relationship.

 

Author Information:

Subhash.K.U, Principal Mentor, Subhash Programming Classes,Bangalore.

VIEW SUBHASH’s PROFILE

SUBHASH LOVES TO TEACH ! CLICK HERE !

 

 

No Comment

You can post first response comment.

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter a message.