Inheritance vs Composition:: Is my understanding correct?
Conceptual differences:
Inheritance:
In case of inheritance, derived class is sub-type of base class.
Meaning if you derive Dog
from Animal
, then Dog
is Animal
and
all* operations that can be performed on Animal
can be performed on Dog
.
- Using
private
, protected
and public
inheritance, however, you can control who knows that Dog
is Animal
and who knows inner workings of Animal
. In case of protected
or private
inheritance only Dog
will know that it is Animal
, but it won't be obvious from the outside.
Composition:
In case of composition one class is included into another.
a Car
is not a Wheel
. But it contains Wheel
. So operations that work on Wheel
will not work on a Car
.
By declaring member variable of type Wheel
as public
, private
or protected
you can control who can access Car
's Wheel
s.
I believe that is clear enough?
Implementation details:
In case of C++, members of base class are included into derived class. Also methods that existed in base class will be accessible in derived class - somewhere. Access specifiers private
, public
and protected
AND inheritance type determine which methods are visible and where.
I thought that there would be only one object
It is one object.
In microsoft compiler and g++ objects are "merged" together, meaning that in case of:
struct Base{
int a;
};
strict Derived: public Base{
int b;
};
Derived
internally will probably (would need to check C++ standard to be sure) have this layout.
strict Derived{
int a;
int c;
};
or
struct Derived{
Base _;
int c;
};
In case of multiple inheritance and diamond inheritance things will get more complicated and base class can be included multiple times.