Virtual constructor and what happens when you call virtual functions inside it

I have two questions, and the answers I found here did not completely satisfy me:

  • Why is declaring a constructor as virtual meaningless?
  • What happens when I call a virtual function from the constructor? Is a virtual table used?
+4
source share
3 answers

When calling the constructor, the real type of the (not yet existing) object is known very accurately. Therefore, calling the constructor will never be indirect. (Only virtual functions are called indirectly when called with a pointer / link.)

BaseClass *x = new SubClass(); 

Calling a virtual function in the constructor does not do what you can expect. Since the subclass has not yet been initialized, the virtual function in the final class cannot be called (currently the v-table points to the class of the executable constructor).

 class BaseClass { BaseClass() { call(); } virtual void call() { std::cout << "BaseClass!"; } }; class SubClass : public BaseClass { SubClass() : BaseClass() { } void call() { std::cout << "SubClass!"; } }; 

http://ideone.com/9aQVIc

+2
source

Why is declaring a constructor as virtual meaningless?

Before the constructor runs, the object does not exist, so there is no override.

What happens when I call a virtual function from the constructor? Is a virtual table used?

He can. In most cases, if the call is made directly from the constructor, the compiler can skip dynamic dispatch, since it knows that the final override is currently located. But he should not perform this optimization, and even if he can do it directly in the constructor, he will not be able to do this if you call a non-virtual function, which, in turn, calls a virtual function. Since a non-virtual function can be called for objects of derived types, it must use a virtual dispatch mechanism.

+3
source

Why declaring a constructor as virtual is meaningless .

When you call the constructor, the virtual table will not be available in memory. Declaring something virtual in C ++ means that it can be overridden by a subclass of the current class, however, the constructor is called when creating the object object, while you cannot create a subclass of the class, which should be creating the class, so there will never be a need declare the constructor virtual. Therefore, in C ++ there is no such thing as a virtual constructor .

What happens when I call a virtual function from a constructor? Is the virtual table used too

See the C ++ FAQ link for a detailed explanation of this issue.

+1
source

All Articles