Gary Gauh
Gary Gauh

Reputation: 5125

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 ?

Upvotes: 3

Views: 142

Answers (3)

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

Const is used in the following way:

Foo inst1;
const Foo inst2;

inst1.fun();    // 1st fun
inst2.fun();    // 2nd fun

Const after the name of the function refers to the implicit this parameter. So, for inst1 it will Foo* and for inst2 const Foo*. This will guide the overload.

The return value is not used for selecting the overload. Methods/functions with the same set of params and different types of return value are not allowed on the same layer.

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490128

For what it's worth, the language from the standard (§13.3.1/3,4):

Similarly, when appropriate, the context can construct an argument list that contains an implied object argument to denote the object to be operated on. Since arguments and parameters are associated by position within their respective lists, the convention is that the implicit object parameter, if present, is always the first parameter and the implied object argument, if present, is always the first argument.

For non-static member functions, the type of the implicit object parameter is

— “lvalue reference to cv X” for functions declared without a ref-qualifier or with the & ref-qualifier

— “rvalue reference to cv X” for functions declared with the && ref-qualifier where X is the class of which the function is a member and cv is the cv-qualification on the member function declaration. [ Example: for a const member function of class X, the extra parameter is assumed to have type “reference to const X”. —end example ]

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

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.

Upvotes: 6

Related Questions