4
class A
{
public:
    ...
    virtual bool Function(..) const {...}
}

class B : public A
{
public:
    ...
    virtual bool Function(..) const {...}
}

class OtherClass
{
public:
    OtherClass(A& a)
    {
        m_bool = a.Function(..);
    }
private:
    bool m_bool;
}

Assume that class A or class B are fully initialized before the construction of class OtherClass.

Question> Is there a problem regarding the calling of a virtual function in the constructor of OtherClass?

Puppy
  • 144,682
  • 38
  • 256
  • 465
q0987
  • 34,938
  • 69
  • 242
  • 387

3 Answers3

5

No, why should there be any problem? The instance of A passed (via reference) to the constructor of OtherClass is already fully initialized, so virtual functions on it work as expected.

The warning you heard is about calling virtual functions of the object you are constructing inside its constructor; in this case, virtual dispatch is disabled, i.e. in the constructor of each base class the virtual function version called is the one of the base class whose constructor is running.

The idea is that, inside a base class constructor, the object isn't yet become of its final type; in other words, while you are constructing an object that inherits from some base class, it starts as the "basest" type, and transitions to derived types when each derived-class constructor is run. This reflects in what versions of virtual functions the various constructors see when they are run.

You can read about it in more detail here.

Again, this does not affect any object that is passed to the constructor, since they are already fully constructed, so their "definitive type" (and thus the corresponding set of virtual functions) is already completely established.

Community
  • 1
  • 1
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
2

If the functions are defined and not pure virtual functions or abstract base classes, the function call should be fine. the a object will call its virtual function as expected, so to answer your question, no.

Syntactic Fructose
  • 18,936
  • 23
  • 91
  • 177
0

Calling virtual function of A/B has nothing to do with whether it's called from OtherClass's constructor or anywhere else. So no issue.

excalibur
  • 924
  • 2
  • 11
  • 26