Base and derived class having constructors - Inheritance

Q.  In case of inheritance where both base and derived class are having constructors, when an object of derived class is created then___________ .
- Published on 19 Jul 15

a. constructor of derived class will be invoked first
b. constructor of base class will be invoked first
c. constructor of derived class will be executed first followed by base class
d. constructor of base class will be executed first followed by derived class

ANSWER: constructor of base class will be executed first followed by derived class
 

    Discussion

  • Manjinder Singh   -Posted on 16 Sep 16
    Nihal has already written a code to show you the credebility of the answer. But I'll write why does the hierarchy of calling constructors and destructors goes this way?

    When you derive something from a base class you are deriving all the members of the base class. But none among them comes into existence till (some constructor or other mechanism) allots them a memory region. Since, the base members are the part of base class, so only the base class constructor can settle them in memory ( I don't know about public members however). So when you derive them, they should be existing somewhere.

    //So, Base()
    //then Derived()

    Similar goes with destructor. Think about a situation where you are using A Data Member Of Base In Calculating A Data Member Of Derived, & you call ~Base() ... ooops.. All the Base Members will be vanished from the memory at once. :\ .
    So the destructor hierarchy goes,

    ~Derived()
    ~Base()
  • Nihal   -Posted on 08 Oct 15
    Constructor of base class will be executed first followed by derived class means constructors are executed in their order of derivation. Destructors are executed in reverse order of derivation.
    Example:
    class A
    {
    public:
    A()
    {
    cout<<" I am in constructor A\n";
    }
    };
    class B:public A
    {
    public:
    B()
    {
    cout<<" I am in constructor B\n";
    }

    };
    class C: public B
    {
    public:
    C()
    {
    cout<<" I am in constructor C\n";
    }
    };
    void main()
    {
    C obj;
    }

    Output:
    I am in constructor A
    I am in constructor B
    I am in constructor C

Post your comment / Share knowledge


Enter the code shown above:
 
(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)