3

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 Answers2

7

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.
Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

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.

Community
  • 1
  • 1
outis
  • 75,655
  • 22
  • 151
  • 221
  • @Oxsnarder, It's almost the same as calling a non-virtual method within a constructor, which is something people do all the time. It's up to the constructor to ensure it has the object's state as required by the methods it calls before it calls them. Whether the methods are virtual or not isn't really a factor, except that it can confuse programmers about which method (i.e. in which class) is actually called and/or may result in an illegal call to a pure virtual method (i.e. one that doesn't have a body in the current class or any base classes during the constructor). – Leo Davidson Dec 11 '10 at 09:30