Home > Backend Development > C++ > body text

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

Patricia Arquette
Release: 2024-11-09 10:41:02
Original
395 people have browsed it

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

Virtual Function Default Argument Behavior: An Unforeseen Conundrum

In this code snippet, a dilemma arises regarding the behavior of virtual function default arguments:

class B {
public:
    B();
    virtual void print(int data = 10) {
        cout << endl << "B--data=" << data;
    }
};

class D : public B {
public:
    D();
    void print(int data = 20) {
        cout << endl << "D--data=" << data;
    }
};

int main() {
    B* bp = new D();
    bp->print();
    return 0;
}
Copy after login

Expected Output:

[ D--data=20 ]
Copy after login

Actual Output:

[ D--data=10 ]
Copy after login

Understanding the Behavior:

The C standard dictates in section 8.3.6.10 that a virtual function call's default arguments are determined by the static type of the pointer or reference denoting the object. In this instance, since the print function is invoked through a pointer of type B (bp), the default argument of B::print is utilized, resulting in the unexpected output.

Conclusion:

When invoking virtual functions through pointers or references, the default argument behavior must be carefully considered. The static type of the pointer or reference determines which default arguments are used, which can lead to unexpected results if not properly understood.

The above is the detailed content of Why Does a Virtual Function Call Inherit the Default Argument 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