Unexpected Default Argument Behavior in Virtual Functions: Understanding the Root Cause
In this code snippet, you encounter an intriguing issue related to the default arguments of virtual functions. Despite expecting the output to be "D--data=20," you observe "D--data=10" instead. Let's delve into the internal mechanism to comprehend the root cause.
In your example, you have two classes, B and D, with a virtual function named print that takes a default argument. In class D, you override the print function and provide a different default argument. When you create an instance of D, you access the print function through a pointer to B.
According to the C standard (8.3.6.10), "A virtual function call uses the default arguments in the declaration of the virtual function determined by the static type of the pointer or reference denoting the object." This implies that when calling a virtual function through a pointer to a base class, it uses the default arguments defined in the base class's declaration, regardless of the overridden default arguments in the derived class.
Therefore, when you call print through the pointer bp, the default argument is determined by the static type of bp, which is B. Consequently, the default argument of B::print is used, resulting in the output of "D--data=10" instead of the expected "D--data=20."
The above is the detailed content of Why Does the Default Argument of a Virtual Function Use the Base Class Value?. For more information, please follow other related articles on the PHP Chinese website!