Can a C++ virtual functions have default parameters?

C++Server Side ProgrammingProgramming

Yes, C++ virtual functions can have default parameters.

Example Code

 Live Demo

#include<iostream>
using namespace std;
class B {
   public:
      virtual void s(int a = 0) {
         cout<<" In Base \n";
      }
};

class D: public B {
   public:
      virtual void s(int a) {
         cout<<"In Derived, a="<<a;
      }
};

int main(void) {
   D d; // An object of class D
   B *b = &d;// A pointer of type B* pointing to d
   b->s();// prints"D::s() called"
   return 0;
}

Output

In Derived, a=0

In this output, we observe that, s() of derived class is called and default value of base class s() is used.

Default arguments do not participate in signature of functions. So signatures of s() in base class and derived class are considered same, hence base class’s s() is overridden. Default value is used at compile time. When compiler checks that an argument is missing in a function call, it substitutes the default value given. Therefore, in the above program, value of x is substituted at compile time, and at run time derived class’s s() is called. Value of a is substituted at compile time, and at run time derived class’s s() is called.

raja
Published on 03-Apr-2019 14:49:10
Advertisements