Calling the base C ++ constructor with a parameter to be created in the derived constructor

QUESTION 1)

class Base { Base(std::string name); virtual std::string generateName(); } class Derived : Base { Derived(); virtual std::string generateName(); } 

the question arises:

which method will be called on generateName ()?

 Derived :: Derived : Base(generateName()) { //what method will be called on generateName() ? } 

QUESTION 2)

How can I do it? if the default constructor should accept a parameter, but do I need to generate this parameter in the Derived constructor?

+5
source share
2 answers

First, a solution: use a static member function or a function without a member.

As for the behavior, Derived::generateName() will be called. A long sentence in the C ++ standard that defines this behavior says (C ++ 03 12.7 / 3):

When a virtual function is called directly or indirectly from a constructor (including from a mem initializer for a data element) or from a destructor, and the object to which the call is applied is an object that is under development or destruction, the called function is the one a constructor or destructor or one of its bases is defined, but not a function that overrides it in a class derived from the constructor or destructor class, or overrides it in one of the other base classes of the derived object itself.

Since the constructor executed during the virtual call is the Derived constructor, Derived::generateName() called.

Now the deleted answer rightly refers to an article by Scott Meyers, which recommends "Never call virtual functions during construction or destruction." The rules for what is called call forwarding are complex and hard to remember.

+8
source

Take two ...

I made a run with calls to generateName() in the base class initializer and both constructors. Exit left me confused:

 Derived (called from Derived Base initializer) Base (called from Base ctor) Derived (called from Derived ctor) 

I never thought that a class could turn from a derivative into a base, and then back to a derivative in the same build sequence. Every day you learn something new.

+1
source

All Articles