Virtual Function Default Argument Behavior: An Unforeseen Conundrum
In this code snippet, a dilemma arises regarding the behavior of virtual function default arguments:
class B { public: B(); virtual void print(int data = 10) { cout << endl << "B--data=" << data; } }; class D : public B { public: D(); void print(int data = 20) { cout << endl << "D--data=" << data; } }; int main() { B* bp = new D(); bp->print(); return 0; }
Expected Output:
[ D--data=20 ]
Actual Output:
[ D--data=10 ]
Understanding the Behavior:
The C standard dictates in section 8.3.6.10 that a virtual function call's default arguments are determined by the static type of the pointer or reference denoting the object. In this instance, since the print function is invoked through a pointer of type B (bp), the default argument of B::print is utilized, resulting in the unexpected output.
Conclusion:
When invoking virtual functions through pointers or references, the default argument behavior must be carefully considered. The static type of the pointer or reference determines which default arguments are used, which can lead to unexpected results if not properly understood.
The above is the detailed content of Why Does a Virtual Function Call Inherit the Default Argument from the Base Class Instead of the Derived Class?. For more information, please follow other related articles on the PHP Chinese website!