Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call a virtual function in a constructor?

I know that a call of virtual function in constructors can cause undefined behavior. However, calling virtual function with a scope modifier is OK?

class A
{

public:
A() { A::f(); }
virtual void f();

};

class B
{

public:
B() { B::f(); }
virtual void f();

};

I think it is not different from calling a non-virtual function and it doesn't have any problems. Is it right? Or Did I overlook something?

like image 963
Gimun Eom Avatar asked Dec 05 '25 04:12

Gimun Eom


1 Answers

You are OK with your calls to A::f() in A::A() and to B::f() in B::B(). The virtual call mechanism is not used when the functions are called with explicit qualification.

This is what the draft standard says about using explicit qualification when calling a virtual function:

10.3/15 Explicit qualification with the scope operator (5.1) suppresses the virtual call mechanism. [ Example:

class B { public: virtual void f(); };
class D : public B { public: void f(); };
void D::f() { / ... / B::f(); }

Here, the function call in D::f really does call B::f and not D::f. —end example ]

like image 128
R Sahu Avatar answered Dec 07 '25 18:12

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!