I have two questions and the answers I found here didn't totally satisfy me:
- Why declaring a constructor as virtual is meaningless?
- What happens when I call a virtual function from a constructor? Is the virtual table used too?
I have two questions and the answers I found here didn't totally satisfy me:
Why declaring a constructor as virtual is meaningless?
Before the constructor is executed, the object does not exists, so there is no such thing as an override.
What happens when I call a virtual function from a constructor? Is the virtual table used too?
It can. In most cases, if the call is directly performed from the constructor the compiler can skip the dynamic dispatch, as it knows what the final overrider is at this point. But it need not perform that optimization, and even if it can do that in the constructor directly, it cannot do it if you call a non-virtual function that in turn calls the virtual function. Because the non-virtual function might be called for objects of derived types it must use the virtual dispatch mechanism.
When calling a constructor, the actual type of the (not yet existing) object is known for very sure. So calling a constructor will never be indirect. (Only virtual functions are called indirectly when called via a pointer / reference.)
BaseClass *x = new SubClass();
Calling a virtual function in a constructor doesn't do what you might expect. As the subclass hasn't been initialized yet, the virtual function on the final class can't be called (the v-table currently points to the class of the constructor currently being executed).
class BaseClass {
BaseClass() {
call();
}
virtual void call() {
std::cout << "BaseClass!";
}
};
class SubClass : public BaseClass {
SubClass() : BaseClass()
{
}
void call() {
std::cout << "SubClass!";
}
};
Why declaring a constructor as virtual is meaningless
.
When the constructor is invoked the virtual table would not be available in the memory. Declaring something virtual in C++ means that it can be overridden by a sub-class of the current class, however the constructor is called when the objected is created, at that time you can not be creating a sub-class of the class you must be creating the class so there would never be any need to declare a constructor virtual. Therefore, there is no such a thing as virtual constructor
in C++.
What happens when I call a virtual function from a constructor? Is the virtual table used too
See C++ FAQ link about detailed explanation of this question.