In C , virtual functions allow derived classes to override the implementations of functions defined in base classes. However, the default argument behavior for virtual functions can be confusing.
Problem Description:
Consider the following code snippet:
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 ]
Explanation:
According to the C standard (8.3.6.10), when calling a virtual function through a pointer or reference, the default arguments are derived from the static type of the pointer or reference, not the derived class's overriding function.
In this case, bp is a pointer of type B, so the default argument of B::print (which is 10) is used, overriding the default argument of D::print (which is 20).
Therefore, the output is D--data=10 instead of the expected D--data=20.
The above is the detailed content of Why Does a Virtual Function's Default Argument Use the Base Class's Value Instead of the Derived Class's?. For more information, please follow other related articles on the PHP Chinese website!