I know that virtual methods behave in constructors not at all as expected. But it’s not quite clear to me whether it is possible to call a virtual method in the constructor of a derived class?

Like this:

class A { public: virtual void f() = 0; int a; }; class B : public A { public: B() { f(); } void f() override { cout << "B::f()" << endl; } int b; }; 

Can there be problems in this case? If so, what will they be?

  • AND? This code contains ads only. What could be "problems" in code that does nothing? - AnT 4:44 pm
  • one
    You can call, it just will not be virtual. The method from the same class will be called. Calling a virtual method from another class in the hierarchy is also possible with an explicit specification, for example B::f(); . - freim
  • @freim: Why would it suddenly "not be virtual"? - AnT pm
  • @AnT, you love to get to the bottom of nothing. He will be called as non-virtual - will arrange such a wording? - freim 5:58 pm

1 answer 1

It is not clear what kind of problems you are talking about.

As has been said more than once, the mechanism for invoking virtual methods in constructors works as if the dynamic type of an object is determined by the constructor that is currently working. In all other respects, the virtual mechanism works as usual.

In your example, in accordance with this rule, during the operation of the constructor of class B from the point of view of the virtual mechanism, the constructed object will be of type B Accordingly, the virtual call of the method f from the constructor B::B falls into the implementation of B::f .

There are no problems here.

In such a trivial example as yours, most compilers immediately "guess" that it is the B::f method that will be called and optimize the virtual call, replacing it with the usual direct call. In more tricky cases (such as a call through a pointer), the call will remain virtual, but it will still work correctly (considering the above).

Cm.
Calling a virtual method in the constructor
Strange and incomprehensible mistake

  • Thanks more for the clarification. Then I don’t quite understand why everyone says that it’s impossible to call virtual methods in constructors ... The fact that the constructor uses the method of the class whose constructor is currently working is quite understandable. It is obvious that in the constructor of the ancestor it will not be possible to call the virtual method of the successor, because the successor does not exist yet. Actually, that's why I don’t understand what the problems might be. - MGNeo 7:05 pm
  • one
    @MGNeo: "everyone says that calling virtual methods in constructors is impossible" is nonsense. Do not listen to such "all". Of course, you can call. It is only necessary to understand how this will work with such a call. - AnT
  • thank you for help! - MGNeo