Understanding Overload Resolution

Overloading Functions with Default Arguments

Can I overload functions that differ only in their default arguments?

Illustration representing computer hardware

No, you cannot overload functions that differ only in their default arguments. If you try to do this, you will get a compilation error due to ambiguity. For example:

#include <iostream>

void Print(int x) {
  std::cout << "Print(int)";
}

void Print(int x, int y = 0) {
  std::cout << "Print(int, int)";
}

int main() {
  Print(10);// error: ambiguous call
}
error: 'Print': ambiguous call to overloaded function

In this case, both Print(int) and Print(int, int) are equally valid for the call Print(10), because the second parameter of Print(int, int) has a default value. This creates an ambiguity, and the compiler will emit an error.

To avoid this, ensure that your overloaded functions differ in their parameter types or number of parameters, not just in their default arguments.

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

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