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.
Answers to questions are automatically generated and may not have been reviewed.
Learn how the compiler decides which function to call based on the arguments we provide.