Understanding Overload Resolution

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?

Illustration representing computer hardware

When you pass a non-const variable (like a non-const int) to an overloaded function, and one overload takes a non-const reference (int&) while another takes a const reference (const int&), the compiler will prefer the non-const reference overload.

This is because binding a non-const reference to a non-const variable is considered an exact match, while binding a const reference to a non-const variable requires a trivial conversion (adding const).

Here's an example:

#include <iostream>

void Print(int& x) {
  std::cout << "non-const ref overload";
}

void Print(const int& x) {
  std::cout << "const ref overload";
}

int main() {
  int x = 10;
  Print(x);// calls Print(int&)
}
non-const ref overload

The output will be "non-const ref overload", because x is non-const and thus prefers the non-const reference overload.

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