C++ Virtual Functions with Default Parameters



Yes, C++ virtual functions can have default parameters. The default parameter is the value provided during function declaration, such that the value can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and becomes a parameterized argument.

Virtual Function

A virtual function is a member function declared in a base class and can be overridden in a derived class. When we use a pointer or reference to the base class to refer to an object of the derived class, you can call a virtual function for that object. This will execute the version of the function defined in the derived class.

Example of Virtual Function with Default Parameter

The following example, demonstrates the working of the virtual function with default parameter:

#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="<s();// prints"D::s() called"
 return 0;
}

Following is the output of the above code ?

In Derived, a=0

In the above output, the s() function of the derived class is called, but the default argument value from the base class is used.

This happens because default arguments are handled at compile time based on the static type (B*), while virtual function dispatch happens at runtime based on the dynamic type (D). Since b is of type B*, the default value 0 from B::s(int) is used at compile time, and then at runtime, D::s(int) is actually called with a = 0.

Virtual Function with Default Parameter and Overriding

This is another example of a virtual function with default parameters. Here, two numbers are provided as default parameters in the base class, and the sum of these numbers is displayed using the overridden virtual function in the derived class ?

#include<iostream>
using namespace std;
class Base {
public:
   // Virtual function with two default parameters
   virtual void add(int a = 5, int b = 10) {
      cout << "Base Sum: " << (a + b) << endl;
   }
};
    
class Derived: public Base {
public:
   // Override the function (no default values here)
   void add(int a, int b) override {
      cout << "Derived Sum: " << (a + b) << endl;
   }
};
    
int main() {
   Derived d;
   Base * ptr = & d; // Base class pointer pointing to Derived object
   ptr -> add();
   return 0;
}

Following is the output ?

Derived Sum: 15
Updated on: 2025-05-20T19:29:14+05:30

770 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements