Home  >  Article  >  Backend Development  >  How do Default Arguments Behave in Virtual Functions in C ?

How do Default Arguments Behave in Virtual Functions in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-11-10 10:12:02269browse

How do Default Arguments Behave in Virtual Functions in C  ?

Virtual Function Default Argument Behavior

In C , virtual functions provide a mechanism for polymorphism. However, the behavior of default arguments in virtual functions can be confusing.

Consider the following code:

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;
}

When you run this code, you might expect the output to be:

D--data=20

However, the actual output is:

D--data=10

Explanation:

The reason for this unexpected behavior lies in the C standard (8.3.6.10), which states that 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. In this case, since you are calling print() through a pointer of type B (i.e., bp), the default argument of B::print() is used, even though the overridden function in the derived class D has a different default argument.

Therefore, when calling a virtual function through a base class pointer or reference, the default arguments of the base class function, not the overridden function, are applied. This behavior is important to understand to avoid any confusion or unexpected results when working with virtual functions and default arguments.

The above is the detailed content of How do Default Arguments Behave in Virtual Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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