1

class diagram

Currently, I have the "lots of code" as noted in the diagram inside each child's constructor. My goal is to move it to the parent's constructor.

  • No, you should not call virtual methods from constructors or destructors. – juanchopanza May 05 '13 at 10:07
  • possible duplicate of [Calling virtual functions inside constructors](http://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors) – juanchopanza May 05 '13 at 10:08

2 Answers2

10

Is it possible to call a virtual method from an abstract class constructor?

Technically it is possible, but it won't work as you expect, so don't do it, because the virtual table for derived classes has not been constructed yet.

The implementation of the class being constructed is going to be called when a virtual function is invoked from a constructor, and if the virtual function you are calling is pure, you get undefined behavior.

Per paragraph 10.4/6 of the C++11 Standard:

Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined.

Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • Actually, the call to a pure virtual function is UB independently of whether the pure function has an implementation. I.e. Even if you deliberately provide a definition for the pure virtual function, calling it in a way that uses virtual dispatch (i.e. not `classname::`) still causes UB simply because the function is declared pure. – CB Bailey May 05 '13 at 10:26
  • @CharlesBailey: I edited the answer. I just learnt that a pure virtual function can have an implementation :) Thank you for correcting me – Andy Prowl May 05 '13 at 10:28
  • @AndyProwl Effective C++ 3rd Ed. Item 34 has a nice piece on implementation of pure virtual fucntions, but also notes that: "Apart from helping you impress your fellow programmers at a cocktail party, knowledge of this feature is generally of limited utility." Their main use is to provide impure virtual functions with a default implementation, and you have to call them with qualification like this: `derived_object->AbstractBase::draw()`. – TemplateRex May 05 '13 at 19:03
1

If you try to invoke initializeFiles() from the FileContainer constructor it will invoke FileContainer::initializeFiles(). This is because the constructor for the derived class has not been executed yet and therefore the v-table for the derived class has not been built.

Also if FileContainer::initializeFiles() is a pure-virtual function then you will get a crash.

Brian Matthews
  • 8,506
  • 7
  • 46
  • 68