Home > Backend Development > C++ > Why Does the Default Argument of a Virtual Function Use the Base Class Value?

Why Does the Default Argument of a Virtual Function Use the Base Class Value?

Mary-Kate Olsen
Release: 2024-11-12 16:57:01
Original
485 people have browsed it

Why Does the Default Argument of a Virtual Function Use the Base Class Value?

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!

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