Home > Backend Development > C++ > body text

Why Does a Virtual Function Call Inherit Default Arguments from the Base Class Instead of the Derived Class?

Mary-Kate Olsen
Release: 2024-11-09 11:46:02
Original
420 people have browsed it

Why Does a Virtual Function Call Inherit Default Arguments from the Base Class Instead of the Derived Class?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template