Default arguments and virtual function in C++

C++Server Side ProgrammingProgramming

Let’s consider a sample program in C++ for easy under standing of the concept −

Example Code

#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 the 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 the compile time, and at the 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 04-Apr-2019 10:28:48
Advertisements