1

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();
}
SU3
  • 5,064
  • 3
  • 35
  • 66
SGoodman
  • 25
  • 5

1 Answers1

2

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.

SU3
  • 5,064
  • 3
  • 35
  • 66
Arkady Godlin
  • 588
  • 2
  • 9