adspace


How Do you Code Composition and Aggregation in C++ ?

Answer Posted / Shivashish Patel

Composition is a form of association in which an object is part of another object. In C++, composition can be achieved by creating member objects within a class. For example:
```cpp
class Engine {
public:
void start() { cout << "Engine started." << endl; }
};

class Car {
private:
Engine engine;
public:
void drive() { engine.start(); cout << "Car driving." << endl; }
};
```
Aggregation is a form of association in which an object belongs to another object. In C++, aggregation can be achieved by using pointers or references to member objects. For example:
```cpp
class Engine {
public:
void start() { cout << "Engine started." << endl; }
};

class Car {
private:
Engine* engine;
public:
Car(Engine* e) : engine(e) {}
void drive() { engine->start(); cout << "Car driving." << endl; }
};
```
In this example, the `Car` object has a pointer to an `Engine` object. The `Car` constructor takes an `Engine` object as a parameter and assigns it to the `engine` member.

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Please send ford technologies placement paper 2 my mail id

2173


Hi friends I have experience of 6 months in website design and maintanence. Now i am looking for other IT jobs.. to switch platform. please post any interview you know in chennai.

2276