Virtual Function Default Arguments Behavior
In the provided C code, a curious situation arises with virtual function overloading and default arguments. Let's explore the issue and understand the underlying mechanism.
The code defines two classes, B and D, where B has a virtual print method with a default argument of 10 and D overrides print with a different default argument of 20. When calling print through a pointer of type B pointing to an object of type D, the expected output of "D--data=20" is not obtained. Instead, the output displays "D--data=10".
According to the C standard (8.3.6.10), a virtual function call uses the default arguments defined in the declaration determined by the pointer's or reference's static type. This implies that when print is called through a B pointer, it inherits the default argument from B, despite being overridden in D.
The explanation lies in the static type (B) of the pointer, which determines the default argument used during the virtual function call. Even though the object pointed to is of type D, the type of the pointer dictates the default argument behavior.
Therefore, to obtain the desired output "D--data=20", the pointer used to call print must be of type D to ensure the use of the overridden default argument.
The above is the detailed content of Why Does a Virtual Function Call Inherit Default Arguments from the Base Class Instead of the Derived Class?. For more information, please follow other related articles on the PHP Chinese website!