
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Hello World
- C++ Omitting Namespace
- C++ Tokens
- C++ Constants/Literals
- C++ Keywords
- C++ Identifiers
- C++ Data Types
- C++ Numeric Data Types
- C++ Character Data Type
- C++ Boolean Data Type
- C++ Variable Types
- C++ Variable Scope
- C++ Multiple Variables
- C++ Basic Input/Output
- C++ Modifier Types
- C++ Storage Classes
- C++ Numbers
- C++ Enumeration
- C++ Enum Class
- C++ References
- C++ Date & Time
- C++ Operators
- C++ Arithmetic Operators
- C++ Relational Operators
- C++ Logical Operators
- C++ Bitwise Operators
- C++ Assignment Operators
- C++ sizeof Operator
- C++ Conditional Operator
- C++ Comma Operator
- C++ Member Operators
- C++ Casting Operators
- C++ Pointer Operators
- C++ Operators Precedence
- C++ Unary Operators
- C++ Control Statements
- C++ Decision Making
- C++ if Statement
- C++ if else Statement
- C++ Nested if Statements
- C++ switch Statement
- C++ Nested switch Statements
- C++ Loop Types
- C++ while Loop
- C++ for Loop
- C++ do while Loop
- C++ Foreach Loop
- C++ Nested Loops
- C++ break Statement
- C++ continue Statement
- C++ goto Statement
- C++ Strings
- C++ Strings
- C++ Loop Through a String
- C++ String Length
- C++ String Concatenation
- C++ String Comparison
- C++ Functions
- C++ Functions
- C++ Multiple Function Parameters
- C++ Recursive Function
- C++ Return Values
- C++ Function Overloading
- C++ Function Overriding
- C++ Default Arguments
- C++ Arrays
- C++ Arrays
- C++ Multidimensional Arrays
- C++ Pointer to an Array
- C++ Passing Arrays to Functions
- C++ Return Array from Functions
- C++ Structure & Union
- C++ Structures
- C++ Unions
- C++ Pointers
- C++ Pointers
- C++ Dereferencing
- C++ Modify Pointers
- C++ Class and Objects
- C++ Object Oriented
- C++ Classes & Objects
- C++ Class Member Functions
- C++ Class Access Modifiers
- C++ Static Class Members
- C++ Static Data Members
- C++ Static Member Function
- C++ Inline Functions
- C++ this Pointer
- C++ Friend Functions
- C++ Pointer to Classes
- C++ Constructors
- C++ Constructor & Destructor
- C++ Default Constructors
- C++ Parameterized Constructors
- C++ Copy Constructor
- C++ Constructor Overloading
- C++ Constructor with Default Arguments
- C++ Delegating Constructors
- C++ Constructor Initialization List
- C++ Dynamic Initialization Using Constructors
- C++ Inheritance
- C++ Inheritance
- C++ Multiple Inheritance
- C++ Multilevel Inheritance
- C++ Object-oriented
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
- C++ Virtual Function
- C++ Pure Virtual Functions & Abstract Classes
- C++ File Handling
- C++ Files and Streams
- C++ Reading From File
- C++ Advanced
- C++ Exception Handling
- C++ Dynamic Memory
- C++ Namespaces
- C++ Templates
- C++ Preprocessor
- C++ Signal Handling
- C++ Multithreading
- C++ Web Programming
- C++ Socket Programming
- C++ Concurrency
- C++ Advanced Concepts
- C++ Lambda Expression
- C++ unordered_multiset
Default Arguments in C++
Default Arguments
Default arguments in C++ are the values that are assigned to function parameters during function declaration. These default values are automatically assigned when the caller does not provide any arguments for those parameters while calling the function. If a value is provided by the caller during a function call, it will override the default value.
Syntax
return_type function_name(param1 = v1, param2 = v2, ...);
Here
- return_type defines the type of returned value e.g., int, float, void.
- function_name is the name of the function defined by the user
- param1, and param2 are the names of function parameter.
- v1, and v2 are default values assigned to those parameters.
Rules for Default Arguments
Here are the key rules to follow when defining default arguments in C++ to ensure that your code is both efficient and error-free.
1. Default Arguments must be specified in Function Declaration, not Definition.
The first rule says that default arguments must be specified in the function declaration (prototype), not in the function definition (implementation).
In case the default argument is specified in the definition, or if in both the declaration and definition, then it will throw a compilation error.
Example
// Function Declaration with default arguments void greet(string name = "TutorialsPoint"); // Function Definition without default arguments (Correct) void greet(string name) { cout << message << ", " << name << "!" << endl; }
2. Default Arguments must be assigned from Right to Left
When assigning the values for default arguments, it must start from the rightmost parameters to the leftmost ones, where the user can't skip providing parameters in the middle.
Example
// Valid void funcA(int x, string y = "TutorialsPoint"); // Valid void funcB(int x = 2006, string y = "TutorialsPoint" ); // Invalid, because default arguments must be assigned from right to left void funcC(int x = 2006, int y);
3. Default Arguments cannot be Changed or Modified
Once specified default argument in the function declaration, then further it can't be changed or modified in any other declaration or definition. Else it will throw an error.
Example
void func(int x = 10); // First Declaration void func(int x = 20); // Second Declaration, causes error
4. Ambiguity with Function Overloading
Calling the default arguments from overloaded functions can cause ambiguity, making it difficult for the compiler to decide which version of the function to call if the arguments provided are not unique. So for this ensure that functions with default arguments do not conflict with each other in overloads.
Example
void get(string name = "TutorialsPoint"); // function 1 void get(string name = "TutorialsPoint", int num = 2016); // function 2 get(); // Which function should the compiler choose?
Example of Default Arguments
Here is a basic simple example showcasing Default arguments in C++.
#include <iostream> using namespace std; int main() { double price, discount = 12.0; // Default discount cout << "Enter the price of the item: "; cin >> price; double total = price - (price * discount / 100); cout << "The total price after a " << discount << "% discount is: " << total << endl; return 0; }
When the above code is compiled and executed, it produces the following result −
Enter the price of the item: 120 The total price after a 12% discount is: 105.6
Default Argument as an Expression
When defining a function, the user can specify the default values for parameters, where these default values can be a constant value or an expression (involving variables, constants, or function calls), which is evaluated when the function is called.
Example
Here is the following example for the default function argument.
#include <iostream> using namespace std; double total_price(double price, double discount = 12.0) { return price - (price * discount / 100); } int main() { double price; cout << "Enter the price of the item: "; cin >> price; // Calculate the total price with a 12% discount by default double total = total_price(price); cout << "The total price after a 12% discount is: " << total << endl; return 0; }
When the above code is compiled and executed, it produces the following result −
Enter the price of the item: 120 The total price after a 12% discount is: 105.6
Default Argument as a Function Call
Calling a function to determine the default value is known as default argument as a Function Call. This calculates the default value dynamically based on the function's logic or other parameters.
#include <iostream> #include <cmath> // for value of using namespace std; double getDefaultWidth() { return 5.0; } double getDefaultRadius() { return 3.0; } double cuboid_vol(double l, double h, double w = getDefaultWidth()) { return l * w * h; } double cylinder_vol(double h, double r = getDefaultRadius()) { return M_PI * r * r * h; } int main() { double length = 10.0; double height = 7.0; // Volume of Cuboid with default width cout << "Cuboid volume : " << cuboid_vol(length, height) << " cubic units" << endl; // Volume of a cuboid with a custom width cout << "Cuboid volume (custom width): " << cuboid_vol(length, height, 4.0) << " cubic units" << endl; // Volume of cylinder with default radius cout << "Cylinder volume (default radius): " << cylinder_vol(height) << " cubic units" << endl; // Volume of a cylinder with a custom radius cout << "Cylinder volume (custom radius): " << cylinder_vol(height, 6.0) << " cubic units" << endl; return 0; }
When the above code is compiled and executed, it produces the following result −
Cuboid volume : 350 cubic units Cuboid volume (custom width): 280 cubic units Cylinder volume (default radius): 197.92 cubic units Cylinder volume (custom radius): 791.681 cubic units
Advantages of Default Arguments
- It simplifies the function calls by reducing the number of overloads, where users don't need to create multiple overloaded functions when one function can handle different cases by using default values for parameters.
- Default arguments help avoid code duplication and reduce redundancy.
- It improves code readability and increases flexibility, which makes further easier to modify in the future.