Containership in C++ refers to the concept of one class being a member of another class. It involves creating objects of one class within another class to establish a relationship between them. The class that contains the object of another class is known as the container class, while the class being contained is referred to as the contained class.
Containership allows for composition, where objects are composed of other objects. It enables building complex data structures and organizing code by encapsulating related functionality within separate classes.
Here's an example to illustrate containership in C++:
#include <iostream>
// Contained class
class Engine {
public:
void start() {
std::cout << "Engine started." << std::endl;
}
};
// Container class
class Car {
private:
Engine engine;
public:
void startCar() {
engine.start();
std::cout << "Car started." << std::endl;
}
};
int main() {
Car car;
car.startCar();
return 0;
}
In this example, we have two classes: Engine
and Car
. The Engine
class represents an engine and has a member function start()
to start the engine. The Car
class represents a car and contains an object of the Engine
class as a member variable.
Inside the Car
class, there is a member variable engine of type Engine
. The startCar()
function in the Car
class invokes the start()
function of the Engine
class using the engine object. It then proceeds to display a message indicating that the car has started.
In the main()
function, we create an object of the Car
class and call the startCar()
function. This results in the engine is started and the car being started, demonstrating the containership relationship.
Containership allows for building complex and hierarchical relationships between classes, enabling modular design and code organization. It promotes code reuse and encapsulation by composing objects with specific functionality within other classes.
In summary, the main difference between inheritance and containership is the relationship they establish between classes. Inheritance represents an "is-a" relationship, where a derived class is a type of the base class. Containership represents a "has-a" relationship, where one class contains an object of another class. Inheritance promotes code reuse and polymorphism, while containership allows for composing objects together and building complex systems.