Overloading on const-ness of *this

Can I overload member functions based on the const-ness of the object they're called on?

Yes, you can overload member functions based on whether the object they're called on is const or not. This is a powerful feature in C++ that allows you to have different behaviors for const and non-const objects.

When you declare a member function as const, it promises not to modify the object's state. You can then overload the function with a non-const version, which is allowed to modify the object.

Here's an example:

#include <iostream>

class MyClass {
public:
  void Print() const {
    std::cout << "Const version\n";
  }

  void Print() {
    std::cout << "Non-const version\n";
  }
};

int main() {
  MyClass obj;
  const MyClass cobj;

  obj.Print();// calls non-const version
  cobj.Print();// calls const version
}
Non-const version
Const version

In this code, the MyClass has two overloads of the Print function: one const, and one non-const.

When we call Print on a non-const object obj, it calls the non-const version. When we call Print on a const object cobj, it calls the const version.

This allows you to have different implementations for const and non-const objects. The const version might only read the object's state, while the non-const version might modify it.

This overloading based on const-ness is resolved at compile time, based on the static type of the object. It's a different mechanism from virtual functions, which are resolved at runtime based on the dynamic type of the object.

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 Parameters
Can I overload a function based on whether a parameter is const or non-const?
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