Understanding Overload Resolution

Overloading on const-ness of Parameters

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

Illustration representing computer hardware

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.

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