SGoodman
SGoodman

Reputation: 25

c++ abstract classes constructor calls

Can anyone explain to me the constructor calls, in the following code. How is the constructor of abstract class called, when there exist no object for it but only a pointer to the derived class. Is an instance of it created to hold the vtable ?

#include <iostream> 

using namespace std;

class pure_virtual {
  public:
    pure_virtual() {
      cout << "Virtul class constructor called !"  << endl;
    }
    virtual void show()=0;
};

class inherit: public pure_virtual {
  public:
    inherit() {
      cout << "Derived class constructor called !" << endl;
    }
    void show() {
      cout <<"stub";
    }
};

main() {
  pure_virtual *ptr;
  inherit temp;
  ptr = &temp;
  ptr->show();
}

Upvotes: 1

Views: 115

Answers (1)

Arkady Godlin
Arkady Godlin

Reputation: 588

The constructor of the pure_virtual class is called when the constructor of inherit is called. So, when the line inherit temp; is executed, the constructor of the object is being called, because it is a derived class. Then the base class constructor is called first.

So in your case the output will be

Virtul class constructor called !
Derived class constructor called !

and because the void show() is virtual, the correct function is called, which is that of the inherit class.

Upvotes: 2

Related Questions