Home > Backend Development > C++ > Do Default Parameters in Virtual Functions Inherit to Derived Classes?

Do Default Parameters in Virtual Functions Inherit to Derived Classes?

Barbara Streisand
Release: 2024-11-26 14:15:11
Original
181 people have browsed it

Do Default Parameters in Virtual Functions Inherit to Derived Classes?

Can Virtual Functions Have Default Parameters?

Problem:

When declaring a virtual function with default parameters in a base class, do derived classes inherit these defaults?

Answer:

No, defaults in virtual functions are not inherited by derived classes. The default used is determined by the static type of the object when the function is called.

Explanation:

The C Standards (C 03 and C 11) specify that virtual function calls use the default arguments declared in the function definition determined by the static type of the pointer or reference used to invoke the function.

Example:

Consider the following code:

struct Base {
  virtual void f(int a = 7);
};
struct Der : public Base {
  void f(int a);
};
Copy after login

When calling f() through a pointer to a Base object, the default 7 will be used:

Base* pb = new Base;
pb->f(); // uses the default 7
Copy after login

However, when calling f() through a pointer to a Der object, the derived class's default will not be used:

Der* pd = new Der;
pd->f(); // error: no default argument for this function
Copy after login

Practice and Compiler Considerations:

While the C Standards dictate the behavior, some compilers may implement virtual function default parameters differently. However, it is recommended to follow the Standard's guidelines to ensure consistent behavior across compilers.

Code Demonstration:

The following code demonstrates the default parameter behavior:

struct Base { virtual string Speak(int n = 42); };
struct Der : public Base { string Speak(int n = 84); };

int main()
{
    Base b1;
    Der d1;

    Base *pb1 = &b1, *pb2 = &d1;
    Der *pd1 = &d1;
    cout << pb1->Speak() << "\n" // Base 42
         << pb2->Speak() << "\n" // Der 42
         << pd1->Speak() << "\n" // Der 84
         << endl;
}
Copy after login

Output:

Base 42
Der 42
Der 84
Copy after login

The above is the detailed content of Do Default Parameters in Virtual Functions Inherit to Derived Classes?. 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