The Wayback Machine - https://web.archive.org/web/20240820134305/https://www.geeksforgeeks.org/default-arguments-c/
Open In App

Default Arguments in C++

Last Updated : 27 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn’t provide a value for the argument. In case any value is passed, the default value is overridden. 

1) The following is a simple C++ example to demonstrate the use of default arguments. Here, we don’t have to write 3 sum functions; only one function works by using the default values for 3rd and 4th arguments. 

CPP




// 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

Time Complexity: O(1)

Space Complexity: O(1)

Explanation: In statement 1, only two values are passed, hence the variables z and w take the default values of 0. In statement 2, three values are passed, so the value of z is overridden with 25. In statement 3, four values are passed, so the values of z and w are overridden with 25 and 30 respectively.

2) 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:

CPP




// 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;
}


Error: 

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) 
     ^

3) A constructor can contain default parameters as well. A default constructor can either have no parameters or parameters with default arguments.

C++




// 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


Explanation: Here, we see a default constructor with no arguments and a default constructor with one default argument. The default constructor with argument has a default parameter x, which has been assigned a value of 0. 

Key Points:  

  • Default arguments are different from constant arguments as constant arguments can’t be changed whereas default arguments can be overwritten if required.
  • Default arguments are overwritten when the calling function provides values for them. For example, calling the function sum(10, 15, 25, 30) overwrites the values of z and w to 25 and 30 respectively.
  • When a function is called, the arguments are copied from the calling function to the called function in the order left to right. Therefore, sum(10, 15, 25) will assign 10, 15, and 25 to x, y, and z respectively, which means that only the default value of w is used.
  • 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 of Default Arguments:

  • Default arguments are useful when we want to increase the capabilities of an existing function as we can do it just by adding another default argument to the function.
  • It helps in reducing the size of a program.
  • It provides a simple and effective programming approach.
  • Default arguments improve the consistency of a program.

Disadvantages of Default Arguments:

  • It increases the execution time as the compiler needs to replace the omitted arguments by their default values in the function call.


Previous Article
Next Article

Similar Reads

Default Arguments and Virtual Function in C++
Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument. Virtual function is a member function that is declared within a base class and is redefined(Overr
3 min read
Templates and Default Arguments
Default parameters for templates in C++: Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char. #include&lt;iostream&gt; using namespace std; template&lt;class T, class U = char&gt; class A { public: T x; U y; }; int main() { A&lt;char
1 min read
Some Interesting facts about default arguments in C++
Predict the output of following C++ programs. 1) #include &lt;iostream&gt; void init(int a=1, int b=2, int c=3); int main() { init(); return 0; } void init(int a=1, int b=2, int c=3) { std::cout &lt;&lt; a &lt;&lt; ' ' &lt;&lt; b &lt;&lt; ' ' &lt;&lt; c; } The above program looks correct at first glance but will fail in compilation. If function use
1 min read
Template non-type arguments in C++
Prerequisite: Templates in C++ Generally, a C++ template, with a single argument looks like this: template&lt;typename template_name&gt; But it has been seen that a template can have multiple arguments. The syntax for the same would be: template&lt;class T1, class T2, class T3, ........., class Tn&gt; where, n is the number of arguments. It is also
3 min read
When Do We Pass Arguments by Reference or Pointer in C++?
In C++, we can pass arguments to a function as a value, reference (or pointer). Each method has its unique benefits and uses. In this article, we will discuss the application or cases where we should pass the arguments by reference or a pointer. But first, let’s quickly revisit the definitions of pointers and references. Pointers in C++ Pointers ar
4 min read
Command Line Arguments in C++
Command-line arguments are arguments that are passed to a program when it is executed from the command line or terminal. They are provided in the command-line shell of operating systems with the program execution command. The main function of C++ generally can have the following signature: int main(){ // Suitable Code return 0; } But to pass comman
4 min read
Does C++ compiler create default constructor when we write our own?
No, the C++ compiler doesn't create a default constructor when we initialize our own, the compiler by default creates a default constructor for every class; But, if we define our own constructor, the compiler doesn't create the default constructor. This is so because the default constructor does not take any argument and if two default constructors
1 min read
When Does Compiler Create Default and Copy Constructors in C++?
A constructor is a special type of member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) is created. There are 3 types of constructors in C++ Default ConstructorCopy constructorParameterized ConstructorIn C++, the compiler creates a default constructor if we d
3 min read
Default values in a Map in C++ STL
Prerequisite: Map in STLA map is a container which is used to store a key-value pair. By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared. When this map is accessed with the [ ] (e.g map&lt;int,int&gt; mpp; mpp[1]; ) if the key is
2 min read
Is body of a Default Constructor blank in C++?
The answer to this question depends upon 2 scenarios: Scenario 1: When there is a Virtual function in the program: In this scenario, compiler automatically creates virtual table(known as V-Table) and VVPTR(Virtual Void Pointer). V-Table contains the virtual method calls whereas VVPTR contain the address of virtual methods which are present in V-Tab
2 min read
Default Methods in C++ with Examples
If we write a class that has no methods in it, and the class does not inherit from another class, the compiler will add six methods to it automatically. The methods which can be automatically generated by the compiler are: Default Constructor: It is equivalent to an empty default constructor. The default constructor is a constructor which can be ca
6 min read
How Does Default Virtual Behavior Differ in C++ and Java?
Let us discuss how the default virtual behavior of methods is opposite in C++ and Java. It is very important to remember that in the C++ language class member methods are non-virtual by default. They can be made virtual by using virtual keywords. For example, Base::show() is non-virtual in following program and program prints "Base::show() called".
3 min read
Default constructor in Java
Like C++, Java automatically creates default constructor if there is no default or parameterized constructor written by user, and (like C++) the default constructor automatically calls parent default constructor. But unlike C++, default constructor in Java initializes member data variable to default values (numeric values are initialized as 0, bool
1 min read
C++ default constructor | Built-in types for int(), float, double()
A constructor without any arguments or with default values for every argument is treated as the default constructor. C++ allows even built-in types (primitive types) to have default constructors. The function style cast int() is analogous(similar in some way) to casting 0 to the required type.It will be called by the compiler when in need(precisely
2 min read
Default Assignment Operator and References in C++
We have discussed assignment operator overloading for dynamically allocated resources here. In this article, we discussed that when we don't write our own assignment operator, the compiler creates an assignment operator itself that does shallow copy and thus causes problems. The difference between shallow copy and deep copy becomes visible when the
2 min read
Default Constructors in C++
A constructor without any arguments or with the default value for every argument is said to be the Default constructor. A constructor that has zero parameter list or in other sense, a constructor that accepts no arguments is called a zero-argument constructor or default constructor. If default constructor is not defined in the source code by the pr
4 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
7 ways to Initialize Vector in C++
Vectors in C++, like Arrays, are one of the most extensively used entities and to initialize vectors in C++ is one of the most common issues that users face. One of the most commonly used methods for vector initialization is the Array style. But C++, along with this, provides several different methods to initialize a vector. In this post, we have l
6 min read
30 OOPs Interview Questions and Answers (2024)
Object-Oriented Programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
Top 50 C++ Project Ideas For Beginners & Advanced
C++ is one of the most popular programming languages widely used in the software industry for projects in different domains like games, operating systems, web browsers, DBMS, etc due to its fast speed, versatility, lower-level memory access, and many more. Many top companies like Microsoft, Google, Apple, Netflix, etc use C++ to develop their produ
15+ min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key:value pairs. dict = { 1: 'Python', 2: 'dictionary', 3: 'example' }Example: As you can see from the example, data is stored in key:value pairs in dictionaries, which makes it easier to find values. Python dictionaries are essential for efficient data mapping and manipulation in pro
10 min read
vector erase() and clear() in C++
Prerequisite: Vector in C++ Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::clear() The clear() function is used to remove all the elements of the vector container, thus making it size 0. Syntax
6 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we can convert numbers that are stored as strings. Exa
8 min read
unordered_map in C++ STL
unordered_map is an associated container that stores elements formed by the combination of a key value and a mapped value. The key value is used to uniquely identify the element and the mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defined. In simple terms, an unordered_map is like a d
7 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
10 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
9 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Practice Tags :
three90RightbarBannerImg