Introduction to Functions

When to Use Default Arguments in C++ Functions

In what situations is it beneficial to use default arguments for function parameters?

Abstract art representing computer programming

Default arguments can be useful in several scenarios:

  1. When a function has parameters that have a common default value. This allows callers to omit those arguments if they want to use the default.
  2. When you want to extend a function's functionality without breaking existing code. You can add new parameters with default values, and existing callers won't need to change.

For example, consider a function that draws a shape:

void DrawShape(std::string name, int width,
  int height, int x = 0, int y = 0) {
  // Draw the shape...
}

By providing default values for x and y, we make them optional for the caller. Callers can use the defaults for a simple case:

// Draws at (0, 0)
DrawShape("Square", 10, 10);

Or they can provide custom values when needed:

// Draws at (100, 100)
DrawShape("Circle", 15, 15, 100, 100);
This Question is from the Lesson:

Introduction to Functions

Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Introduction to Functions

Learn the basics of writing and using functions in C++, including syntax, parameters, return types, and scope rules.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved