Maroun
Maroun

Reputation: 95958

Calling Virtual methods during construction and destruction

Calling Virtual methods during construction and destruction causes a compiler error? I heard that it is a dangerous thing to do.

I know that if I have a Class Base that defines a virtual method foo(), the resolution of foo() is dynamic in all subclasses of Base. So if the subclass Derived overrides foo() then Derived::foo() is called. So why calling virtual methods during construction/destruction confuses the compiler?

What is the difference between calling them from the constructor, and outside it?

Upvotes: 1

Views: 1133

Answers (2)

Adam Berkan
Adam Berkan

Reputation: 125

During construction of Base(), the derived class hasn't been initialized yet, and doesn't really exist yet. When you call a virtual method, your call will go to Base::foo(). This isn't necessarily wrong, but is often unexpected, hence the general prohibition against it.

Similarly during destruction, Derived is destroyed before ~Base() is called, so again virtual method calls will go to Base::foo(), which is again often unexpected.

Upvotes: 7

Try running this example:

struct base {
   virtual int f() const { return 0; }
   base() { std::cout << f() << "\n"; }
   ~base() { std::cout << f() << "\n"; }
};
struct derived : base {
   const int value;
   derived(int v) : value(v) {}
   virtual int f() const { return value; }
};
derived d(100);       // What should this print?

The problem is that when the constructor of the base type is running the type of the object is still base, and not derived. Dispatch will not hit the final-overrider (from the point of view of the user, that has only created a derived object). The same happens in destruction.

Upvotes: 5

Related Questions