Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual Constructor Idiom - Virtuous Or Complete Utter Fallacy

One of the golden rules in C++ is that the life-time of an instance begins when its constructor completes successfully and ends when its destructor begins.

From this rule we conclude that it is NOT a good idea to call virtual methods in a constructor as the possible derived instance is not valid which would lead to undefined behavior.

The Virtual Constructor Idiom as mentioned in C++ FAQ 20.8 seems to indicate the contrary.

My question is:

  • What is the exact definition in the standard for defining the life time of objects relative to calls from their constructors and destructors?
  • and furthermore is the So called "Virtual Constructor Idom" valid?

2 Answers

I think you're confusing two separate (if vaguely related) things.

  1. It is well-known that one shouldn't call virtual functions from constructors (directly or indirectly), for reasons discussed here.
  2. What the FAQ is talking about is calling a constructor from a virtual function. In some sense it is the opposite of #1. The idea is to choose the constructor (i.e. the class) based on the dynamic type of some existing object.
like image 84
NPE Avatar answered Jun 27 '26 08:06

NPE


An object exists as the type of the class the constructor belongs to when the constructor starts, the object just may be in an inconsistent state (which is fine, as execution is currently inside one of the object's methods). That is, an object that is actually of type Derived that inherits from Base is treated as a Base in Base constructors; this in any Base::Base() is treated as a Base *, no matter the actual type of the object that this points to. Calling virtual methods is fine. In a constructor, the virtual methods for the constructor's class will be called, rather than for the actual type of the object.

Your first question is covered in "Base class on the initialisation list of a derived class' copy constructor". The short answer is it's covered by § 12.7 2-3 of C++03.

The virtual constructor idiom is completely valid.

like image 33
outis Avatar answered Jun 27 '26 08:06

outis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!