Can Virtual Functions Have Default Parameters?
Problem:
When declaring a virtual function with default parameters in a base class, do derived classes inherit these defaults?
Answer:
No, defaults in virtual functions are not inherited by derived classes. The default used is determined by the static type of the object when the function is called.
Explanation:
The C Standards (C 03 and C 11) specify that virtual function calls use the default arguments declared in the function definition determined by the static type of the pointer or reference used to invoke the function.
Example:
Consider the following code:
struct Base { virtual void f(int a = 7); }; struct Der : public Base { void f(int a); };
When calling f() through a pointer to a Base object, the default 7 will be used:
Base* pb = new Base; pb->f(); // uses the default 7
However, when calling f() through a pointer to a Der object, the derived class's default will not be used:
Der* pd = new Der; pd->f(); // error: no default argument for this function
Practice and Compiler Considerations:
While the C Standards dictate the behavior, some compilers may implement virtual function default parameters differently. However, it is recommended to follow the Standard's guidelines to ensure consistent behavior across compilers.
Code Demonstration:
The following code demonstrates the default parameter behavior:
struct Base { virtual string Speak(int n = 42); }; struct Der : public Base { string Speak(int n = 84); }; int main() { Base b1; Der d1; Base *pb1 = &b1, *pb2 = &d1; Der *pd1 = &d1; cout << pb1->Speak() << "\n" // Base 42 << pb2->Speak() << "\n" // Der 42 << pd1->Speak() << "\n" // Der 84 << endl; }
Output:
Base 42 Der 42 Der 84
The above is the detailed content of Do Default Parameters in Virtual Functions Inherit to Derived Classes?. For more information, please follow other related articles on the PHP Chinese website!