Inheritance expresses an "is-a" relationship, so that all objects of class derived
ARE objects of class base
. derived
objects have all of the data and methods that base
objects do, plus the data and methods explicitly declared in the derived
class declaration.
It's perfectly possible (and common) to write Derived
classes that depend on the implementation of their Base
classes. For example, suppose that we have
class Base {
public:
Base() { n = 5; }
int GetN() const { return n; }
private:
int n;
};
class Derived : public Base {
public:
Derived() { m = GetN() * 2; }
int GetM() const { return m; }
private:
int m;
};
Now we'd expect
Derived* d = new Derived();
std::cout << d->GetM() << std::endl;
to print 10
, which is exactly what it should do (barring any mistakes on my part). This is a totally reasonable (if a little contrived) thing to do.
The only way the language can get code like this to work properly is to run the Base
constructor before the Derived
constructor when constructing an object of type Derived
. This is because the Derived
constructor depends on being able to call the GetN()
method, which it inherits from Base
, the proper functioning of which depends on the data member n
having been properly initialised in the Base
constructor.
To summarise, when constructing any Derived
object, C++ must construct it as a Base
object first because Derived
is-a Base
and will generally depend on it's implementation and data.
When you do
base* b = d;
in your code, you're declaring a variable b
that is of type "pointer to a base
object" and then initialising this variable with the same memory address held in d
. The compiler doesn't mind you doing this because all derived
objects ARE base
objects, so it makes sense that you might want to treat d
as a b
. Nothing actually happens to the object here though, it's simply a declaration and instantiation of a pointer variable. The object pointed to by d
already was a base
object, since all derived
objects are base objects.
Note that this explanation is intentionally a little fuzzy round the edges and is nowhere near a full explanation of the relationship between base and derived classes in C++. You'll want to go looking in other articles/books/the standard for that. I hope this is relatively easy to understand for beginners though.