I have 2 classes Base and Derived (derived publically from Base).
When I write –
Derived * d1 = new Derived;
delete d1;
Compiler sees that d1 is a Derived type object. So it calls the derived class constructor (which calls the base class constructor). I have 2 questions here –
1) Why do we follow this order?
2) How do these constructors work together to allocate memory? I need some implementation details
Now the next statement is delete d1. So compiler sees that d1 is a derived type object and so calls the destuctor of derived class (which calls the destructor of base class after deleting the derived class members). I have one question here –
1) How do these destructors work together? Lets say the derived class destructor is passed the address of d1 in memory. How do these destructors free up the space now?
(1) The base class does not depend on the derived class, but the other way around is possible. I.e. a
Baseclass cannot know which fields anyDerivedclass has, soBase::Basewon’t and can’t touch them. The other way around is possible,Derived::Derivedcan accessBase::member. Therefore,Base::memberis initialized byBase::BasebeforeDerived::Derived gets the chance to useBase::member`.(2) constructors don’t allocate memory. That’s
new‘s task. Or if the object is a global, the compilers’. The constructor is called withthisalready pointing to the allocated memory; it need just fill in the members at that location.In the case of a base and derived constructor, one common implementation inserts the call to the Base constructor in the generated code for the Derived constructor. With single inheritance, the Base and Derived class usually share the same
thispointer, so the Derived constrcutor can then pass the same pointer that it got.(1) [sic] Just like constructors don’t allocate memory, destructors don’t free it. That’s the task of
delete– and again, for globals the compiler would do it.