Reputation: 441
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?
Upvotes: 3
Views: 147
Reputation: 206567
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 callB::f
and notD::f
. —end example ]
Upvotes: 2
Reputation: 75545
Your example is fine, with the understanding that it will behave exactly as if you were calling a non-virtual function. I assume this is your intent.
Upvotes: 1