Overloading on const-ness of Parameters

Can I overload a function based on whether a parameter is const or non-const?

Yes, you can overload a function based on the const-ness of its parameters. This is because in C++, const is part of the type system, and a const type is considered distinct from its non-const counterpart.

Here's an example:

#include <iostream>

void Print(int& x) {
  std::cout << "Non-const reference parameter";
}

void Print(const int& x) {
  std::cout << "Const reference parameter";
}

int main() {
  int a = 10;
  const int b = 20;

  Print(a);// calls Print(int&)
  Print(b);// calls Print(const int&)
}
Non-const reference parameter
Const reference parameter

In this code, we have two overloads of Print, one taking a non-const reference (int&) and the other taking a const reference (const int&).

When we call Print(a), a is a non-const int, so it matches Print(int&) exactly.

When we call Print(b), b is a const int. It cannot bind to int& because that would discard the const-ness, so it instead matches Print(const int&).

This allows you to provide different implementations depending on whether the parameter is const or not. For example, the non-const version might modify the parameter, while the const version would only read it.

However, note that this only applies to reference (or pointer) parameters. For parameters passed by value, the const-ness does not matter for overload resolution, because the parameter is always copied.

Understanding Overload Resolution

Learn how the compiler decides which function to call based on the arguments we provide.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Passing Non-Const References to Overloaded Functions
Why does the compiler prefer a non-const reference parameter over a const reference when I pass a non-const variable?
Overloading Functions with Default Arguments
Can I overload functions that differ only in their default arguments?
Debugging Overload Resolution Failures
How can I debug a situation where the compiler is not selecting the overload I expect it to?
Overload Resolution with Function Templates
How does overload resolution work when there are both function templates and non-template functions?
Overloading on const-ness of *this
Can I overload member functions based on the const-ness of the object they're called on?
Overloading in Derived Classes
If I overload a function in a base class, can I also overload it in a derived class?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant