From Thinking in C++ Vol. 1 (P-33):
Composition comes with a great deal of flexibility. The member
objects of your new class are usually private, making them
inaccessible to the client programmers who are using the class. This
allows you to change those members without disturbing existing
client code.
You can also change the member objects at runtime, to
dynamically change the behavior of your program. Inheritance,
which is described next, does not have this flexibility since the
compiler must place compile-time restrictions on classes created
with inheritance.
How can we change the member objects at run time in composition?
Aren’t the objects included when the class declaration are written?
class car
{
private:
engine obj;
}
So, here the class car contains the object of class engine. How can we change this at runtime?
Or am I missing some point?
Try using a pointer to your member object instead:
Now you can choose at runtime whether to use an instance of
rotary_engineorv8_engineorflux_capacitor_engine.Of course you may want to use something like a
unique_ptror ashared_ptrto manage the ownership and lifetime of the member object.