Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are default arguments?
2.1.
Example
2.1.1.
Explanation
3.
Characteristics of Default Argument in C++
4.
Rules of Default Arguments in C++
4.1.
1. Argumentation
4.2.
2. Matching Declarations
4.3.
3.  Unique Overloads
4.4.
4. No Default for Reference Parameters
5.
Working of Default Argument in C++
5.1.
1. Function Declaration
5.2.
2. Function Definition
5.3.
3. Function Calling
5.4.
4. Reduction of Function Overloading
6.
Advantages of default argument in C++
7.
Disadvantages of default argument in C++
8.
Virtual Function in C++
8.1.
Rules for Virtual Functions
8.1.1.
Example
9.
Frequently Asked Questions
9.1.
What are the two types of arguments in C++?
9.2.
What is the first argument in C++ main?
9.3.
What is default vs zero argument constructor?
9.4.
What is default in C++ function?
9.5.
What is a default constructor in C++?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

# Default Arguments and Virtual Function in C++

Rahul Singh
0 upvote
Basics of C++
Free guided path
9 chapters
99+ problems
Earn badges and level up

## Introduction

In this article, we will learn about the basic functioning of default arguments and virtual functions followed by the participation of default arguments in the case of virtual functions.

Let us first understand the basic meanings of both terms in C++ to get a better understanding of the concept.

Also See,Fibonacci Series in C++

## What are default arguments?

A default arguments is a predetermined value in a function's declaration. Without a particular argument for that parameter, the function uses the default setting whenever it is called. The default value, however, is overridden if a value is given when calling the function.

### Example

``````#include <iostream>
using namespace std;
void sum(int x, int y = 10, int z = 20)
{
cout << (x + y + z); // returns the sum of x, y, z
}

int main()
{
sum(10); // outputs 40 as x=10, y=10 and z=20
sum(10, 20, 30); // outputs 60 as x=10, y=20, z=30
}``````

#### Explanation

• The 'x', 'y', and 'z' parameters of the sum function have default values of 'y' and 'z,' respectively.

• We use two different sets of arguments to call the sum function twice in the main function.

• When we call sum(10) with just one input, 'x' is set to 10, and 'y' and 'z' are both set to their default values (10 and 20, respectively), producing an output of 40.

• When calling sum(10, 20, 30) with all three arguments supplied, the values of 'x', 'y', and 'z' are set to 10, 20, and 30, respectively, and the output is 60.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

## Characteristics of Default Argument in C++

Characteristics of default arguments in C++ are:

• The default argument values are not final; they can be changed during runtime.

• The function call involves copying the values in a left-to-right sequence.

• All the values with default value will be on the right.

• Default arguments enable flexibility by allowing functions to be called with fewer arguments.

Also Read - C++ Interview Questions

## Rules of Default Arguments in C++

Rules of default arguments in C++ are:

### 1. Argumentation

When defining a function, default values must come after parameters without default values.

``````// Correct: Non-defaulted parameter 'x' comes before defaulted parameter 'y'.
void e1(int x, int y = 5) {
// Function implementation
}
// Incorrect: Defaulted parameter 'y' comes before non-defaulted parameter 'x'.
void e2(int y = 5, int x) {
// Invalid function definition
}``````

### 2. Matching Declarations

When the function definition and function declaration don't match, function prototypes must utilise default values.

``````
// Function declaration (prototype) with default argument values.
void print_Info(int a, int b = 5, int c = 10);

// Function definition with the same default arguments.
void print_Info(int a, int b, int c) {
// Function implementation
}``````

### 3.  Unique Overloads

A function with default arguments may be overloaded, but each overload must have a different set of parameters.

``````// Overloaded functions with unique parameter lists.
void overloadedEg(int x, int y = 10);
void overloadedEg(int x, double y = 3.14);
void overloadedEg(char c);
// Correct usage with unique parameter combinations.
overloadedEg(5);         // Calls int version with default 'y'.
overloadedEg(5, 3.14);   // Calls int/double version.
overloadedEg('A');       // Calls char version.``````

### 4. No Default for Reference Parameters

Since reference parameters must always connect to a proper object, they cannot have default arguments.

``````// Incorrect: Reference parameter 'ref' cannot have a default argument.
void invalidEg(int& ref = someValue) {
// Invalid function definition
}
// Correct usage of reference parameters without default arguments.
void validEg(int& ref) {
// Function implementation
}``````

## Working of Default Argument in C++

In C++, default arguments allow you provide default settings for function parameter values. When a caller does not supply a value for a parameter in a function call, these default values are applied. Here is how C++ handles default arguments:

### 1. Function Declaration

In the function declaration (prototype), which is generally in the header file, you define the default arguments. The parameter list contains assignments that serve as default parameters.

``void print(int a, int b = 4, int c = 6);``

In this example, the print function has three parameters, but b and c have default values of 4 and 6, respectively.

### 2. Function Definition

You don't need to give default values once more in the function definition (often in the source file). Instead, you provide the entire set of parameters without any default values.

``````void printInfo(int x, int y, int z) {
// Function implementation
}``````

### 3. Function Calling

When calling the function, you can choose to provide values for some or all of the parameters. The default value is applied when a value for a parameter with a default argument is omitted.

``````int main() {
print(5);       // 'x' is 5, 'y' uses default (10), 'z' uses default (20)
print(5, 15);   // 'x' is 5, 'y' is 15, 'z' uses default (20)
print(5, 15, 25); // 'x' is 5, 'y' is 15, 'z' is 25
return 0;
}``````

### 4. Reduction of Function Overloading

Default arguments might lessen the requirement for Function Overloading. You can offer default values for optional parameters in a single function rather than having many overloaded functions with distinct parameter lists.

## Advantages of default argument in C++

Some advantages of default argument in C++ are:-

• Simplified Function Calls: Function calls can be made more brief and understandable by using default arguments, which allow you to call a function with less arguments.

• Reduced Function Overloading: By allowing you to offer many iterations of a function with various default values for the same parameters, default arguments lessen the requirement for function overloading.

• Backward Compatibility: Functions that already exist can have default parameters added to them without causing problems for older code that calls them with less arguments.

• Flexibility: They give you the opportunity to define default values for parameters, which is useful when working with optional arguments in functions.

• Better Code Organization: By combining numerous iterations of a function into a single function with default values, default arguments can streamline code.

## Disadvantages of default argument in C++

Some disadvantages of default argument in C++ are:-

• Ambiguity: When there are several overloaded functions with similar parameter lists, default arguments might cause ambiguity in function calls if they are not used wisely.

• Maintenance Complexity: Complex default values or an overuse of default parameters can make code more difficult to comprehend and maintain.

• Reduced Explicitness: Using default parameters could make it less obvious which arguments are required for a function, which could cause confusion in the code.

• Limitated to the Right: Default arguments must be provided in a right-to-left order, therefore you cannot have a default argument for a parameter if the parameter immediately to the right of it lacks a default value.

• Reference Parameters: Reference parameters, like int&, must always relate to genuine objects, hence they are unable to have default arguments. This restriction may prevent some coding patterns.

## Virtual Functionin C++

A virtual function is a member function in the base class that we expect to redefine in derived classes.
Basically, a virtual function is used in the base class to ensure that the function is overridden. This especially applies to cases where a pointer of the base class points to an object of a derived class.

### Rules for Virtual Functions

• Virtual functions cannot be static and also cannot be a friend function of another class.

• Virtual functions should be accessed using a pointer or reference of base class type to achieve run time polymorphism.

• The prototype of virtual functions should be the same in the base as well as the derived class.

• They are always defined in the base class and overridden in the derived class. The derived class doesn’t need to override (or re-define the virtual function); in that case, the base class version of the function is used.

• A class may have a virtual destructor, but it cannot have a virtual constructor.

#### Example

``````class Base {
public:
void print() {
// code
}
};
class Derived : public Base {
public:
void print() {
// code
}
};
``````

Later, if we create a pointer of Base type to point to an object of Derived class and call the print() function, it calls the print() function of the Base class. In other words, the member function of Base is not overridden.

``````int main() {
Derived derived1;
Base* base1 = &derived1;
// Calls function of Base class
base1->print();
return 0;
}
``````

In order to avoid this, the print() function of the base class is declared as virtual by using the virtual keyword.

``````class Base {
public:
virtual void print() {
// code
}
};
``````

Now let us learn about the combined problem of virtual functions and default arguments with the help of below example:

``````#include<iostream>
using namespace std;
class B {
public:
virtual void s( int x = 0 ) {
cout<<" In Base \n";
}
};
class D: public B {
public:
virtual void s(int a = x) {
cout << "In Derived, x="<<x;
}
};
int main() {
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, x = 0``

You can also compile this code with the help of Online C++ Compiler

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

Default arguments do not participate in the signature of functions. So signatures of s() in the base class and derived class are considered the same; hence base class’s s() is overridden. The default value is used at the compile time.

When the compiler checks that an argument is missing in a function call, it substitutes the default value given. Therefore, in the above program, the value of x is substituted at the compile time, and at the run time, the derived class’s s() is called. The value of a is substituted at compile-time, and at run, time derived class’s s() is called.

Hence, in general, it is a best practice to avoid default values in virtual functions to avoid confusion.

Check out this article - Compile Time Polymorphism and Swap Two Numbers Without Using Third Variable

## Frequently Asked Questions

### What are the two types of arguments in C++?

Actual Arguments and Formal Arguments are the two basic categories of arguments in C++. Formal arguments are variables declared in the function's parameter list that operate as placeholders for data received from actual arguments, whereas Actual Arguments are values or expressions supplied to a function during its call.

### What is the first argument in C++ main?

The first parameter in the main function of a C++ program is normally the number of command-line arguments supplied to the program, known as argc in most cases.

### What is default vs zero argument constructor?

When no constructors are defined, the compiler provides a default constructor, whereas a zero-argument constructor is specifically defined and has no parameters.

### What is default in C++ function?

In programming, a default argument is a value specified in a function declaration. If the calling function doesn't provide a value, the compiler assigns it automatically.

### What is a default constructor in C++?

When no constructors are explicitly defined in a class, the compiler in C++ will build a constructor called as Default Constructor. It sets default values for initializing object instances.

## Conclusion

In this blog, we have thoroughly discussed default arguments and virtual functions in C++. We learned how default arguments are passed in the code; we also discussed the implementation of virtual functions in the code.  We further learned about the rules of implementing virtual functions in C++.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our coursesrefer to the mock test and problems look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Guided path
Free
Basics of C++
9 chapters
104+ Problems
Earn badges and level up
Live masterclass