What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Default Arguments in C++: Syntax, Examples & Advantages

  • May 16, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Anubhav Agarwal
Default Arguments in C++: Syntax, Examples & Advantages

Can you add 2 numbers, 3 numbers, and even more numbers using the same function? Yes! In this article, we will talk about the default arguments in C++ in function declarations.  We will look into multiple examples where we will add multiple numbers count using the same function.

What are Default Arguments in C++?

A default argument in C++ is a value written in the function declaration which gets automatically assigned to the parameter if the calling function doesn't provide a value for that argument. This argument is automatically assigned by the compiler to the respective parameters. In case any value is passed, the default value is overridden. 

In this way, the code becomes flexible to define functions with optional parameters.  So now you have also understood that default arguments are evaluated at the point of function declaration, not at the point of the function call. 

Syntax of default arguments using the sum function example is given below:

int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
    return (x + y + z + w);
}

 

Default Arguments Examples

In the 1st example, we will create a single sum function to add 2 numbers, 3 numbers, and 4 numbers using the default values for the 3rd and 4th arguments. Below is the C++ code given:

// Welcome To Favtutor
// CPP Program to demonstrate Default Arguments
#include<iostream>
using namespace std;

// A function with default arguments,
// it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0) //assigning default values to z,w as 0
{
	return (x + y + z + w);
}

// Driver Code
int main()
{
	// Statement 1
	cout << sum(10, 15) << endl;

	// Statement 2
	cout << sum(10, 15, 25) << endl;

	// Statement 3
	cout << sum(10, 15, 25, 30) << endl;
	return 0;
}

 

Output:

25
50
80

 

In the sum function, default arguments are used for the variables z and w as 0. So, In Statement 1, only two values are passed so the default values will get assigned to variables z as 0 and w as 0. In statement 2, three values are passed so the value of parameter z will get overridden as 25 and the default value of variable w will be used similarly for statement 3.

Let's look at another example. If function overloading is done containing the default arguments, then we need to make sure it is not ambiguous to the compiler, otherwise, it will throw an error. The following is the modified version of the above program:

// Welcome to Favtutor
// CPP Program to demonstrate Function overloading in
// Default Arguments
#include<iostream>
using namespace std;

// A function with default arguments, it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0)
{
	return (x + y + z + w);
}
int sum(int x, int y, float z = 0, float w = 0)
{
	return (x + y + z + w);
}
// Driver Code
int main()
{
	cout << sum(10, 15) << endl;
	cout << sum(10, 15, 25) << endl;
	cout << sum(10, 15, 25, 30) << endl;
	return 0;
}

 

Output:

prog.cpp: In function 'int main()':
prog.cpp:17:20: error: call of overloaded 
'sum(int, int)' is ambiguous
  cout << sum(10, 15) << endl; 
                    ^
prog.cpp:6:5: note: candidate: 
int sum(int, int, int, int)
 int sum(int x, int y, int z=0, int w=0) 
     ^
prog.cpp:10:5: note: candidate: 
int sum(int, int, float, float)
 int sum(int x, int y, float z=0, float w=0) 

 

Here we have overridden the same function, when we will provide only two parameters the compiler will get confused about which sum function to execute and consequently throws an error. The data types of the 3rd and 4th parameters in both functions are different. One has a float and the other has only int.

In the third example, we will work with constructors. A constructor can contain default parameters as well. A default constructor can either have no parameters or parameters with default arguments. The C++ code is given below:

// Welcome to Favtutor
// CPP code to demonstrate use of default arguments in
// Constructors

#include<iostream>
using namespace std;

class A {
	private:
		int var = 0;
	public:
		A(int x = 0): var(x){}; // default constructor with one argument
								// Note that var(x) is the syntax in c++ to do : "var = x"
		void setVar(int s){
			var = s; // OR => this->var = s;
			return;
		}
		int getVar(){
			return var; // OR => return this->var;
		}
};
int main(){
	A a(1);

	a.setVar(2);

	cout << "var = " << a.getVar() << endl;
	
	/* ANOTHER APPROACH:
	A *a = new A(1);

	a->setVar(2);

	cout << "var = " << a->getVar() << endl;
	*/
}

// contributed by Francisco Vargas #pt

 

Here we have two constructors. One with no arguments and the other with only a single argument. The default constructor with the argument has a default parameter x, which has been assigned a value of 0. 

Note that default arguments are different from constant arguments as constant arguments can’t be changed whereas default arguments can be overwritten if required.

Also, once a default value is used for an argument in the function definition, all subsequent arguments to it must have a default value as well. It can also be stated that the default arguments are assigned from right to left. For example, the following function definition is invalid as the subsequent argument of the default variable z is not default.

// Invalid because z has default value, but w after it doesn't have a default value
int sum(int x, int y, int z = 0, int w).

 

Advantages & Disadvantages

Following are some major advantages of default arguments in C++:

  1. We can increase the capabilities of an existing function as we can do it just by adding another default argument to the function.
  2. It can reduce the program size.
  3. It is a simple and effective programming approach.
  4. It can improve the consistency of a program

The only disadvantage is that it increases the execution time as the compiler needs to replace the omitted arguments with their default values in the function call.

Overall, default arguments improve code readability and maintainability. And we have also discussed they are better than function overloading. Default arguments can improve code. But they can also create confusion with which arguments are being provided explicitly.

Conclusion 

So, in this article, we studied various examples where we can implement default arguments in C++, how to create the same function, and deal with multiple counts of parameters using the same function. Happy Learning :)

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Anubhav Agarwal
I'm a research-oriented engaged in various technologies and a technical content writer. Being a coder myself, going through the documentation to provide optimized solutions as technical content is what I always look for.