Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can const make a function overloads?

I wrote this code in C++:

class Foo
{
public:
    int& fun(){return var;}       // 1st fun
    int fun() const {return var;}  // 2rd fun
 private:
    int var;
};
int main()
{
    Foo foo;
    int i = foo.fun();
    return 0;
}

I know that C++ cannot discriminate overloading function by return value,but why when I added a const to 2rd function ,overloading can work ? What the 'const' have done ?

like image 341
Gary Gauh Avatar asked Sep 01 '26 06:09

Gary Gauh


1 Answers

Compiler cannot discriminate by return type because return values can undergo conversion before the assignment is performed. The object on which the function is invoked, on the other hand, is a parameter (albeit an implicit one) to the function, so the compiler can discriminate on it.

like image 88
Sergey Kalinichenko Avatar answered Sep 03 '26 19:09

Sergey Kalinichenko



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!