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?
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 toBase::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 toBase::foo(), which is again often unexpected.