Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const method overloading

I am wandering why C++ chooses to call non const methods on non const object for overloaded methods differing only by const method signature, Namely:

#include<iostream>

class Foo
{
 public:
  Foo() {}
  int bar() const { std::cout<<"const version called"<<std::endl; }
  int bar() { std::cout<<"version called"<<std::endl; }
};

int main()
{
  Foo f;
  f.bar();
  const Foo g;
  g.bar();
  return 0;
}

I understand that for g object, being const, the const version of bar is called. But how about f? The output is

version called
const version called

Thanks for your insights.

like image 514
Juan Chô Avatar asked Mar 26 '26 08:03

Juan Chô


1 Answers

This is how overload resolution works.

First, a list of candidate functions is constructed. In your case it consists of two functions:

int Foo::bar() const;
int Foo::bar();

Each function in the list is converted to accept this argument roughly like this:

int Foo_bar(const Foo* this);
int Foo_bar(Foo* this);

Then the choice is made according to the "Best viable function" (13.3.3) part of the C++ standard, which says, in short, that the best function is the one requiring the least number of conversions for its arguments. So if you have Foo f; and call f.bar(), the best function is the one accepting non-const this, because it requires no conversions, whereas the const version would require a qualification conversion for this from Foo* to const Foo*.

like image 86
Anton Savin Avatar answered Mar 27 '26 21:03

Anton Savin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!