Home > Backend Development > C++ > body text

Why Does a Virtual Function's Default Argument Use the Base Class's Value Instead of the Derived Class's?

Susan Sarandon
Release: 2024-11-09 22:00:03
Original
812 people have browsed it

Why Does a Virtual Function's Default Argument Use the Base Class's Value Instead of the Derived Class's?

Understanding Virtual Function Default Argument Behavior

In C , virtual functions allow derived classes to override the implementations of functions defined in base classes. However, the default argument behavior for virtual functions can be confusing.

Problem Description:

Consider the following code snippet:

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 ]

Actual Output:

[ D--data=10 ]

Explanation:

According to the C standard (8.3.6.10), when calling a virtual function through a pointer or reference, the default arguments are derived from the static type of the pointer or reference, not the derived class's overriding function.

In this case, bp is a pointer of type B, so the default argument of B::print (which is 10) is used, overriding the default argument of D::print (which is 20).

Therefore, the output is D--data=10 instead of the expected D--data=20.

The above is the detailed content of Why Does a Virtual Function's Default Argument Use the Base Class's Value Instead of the Derived Class's?. 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