Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ member functions with same name and parameters, different return type

Tags:

c++

is it valid if I define member functions with same name&parameters but different return types inside a class like this:

class Test {
public:
    int a;
    double b;
}

class Foo {    
private:
    Test t;
public:
    inline Test &getTest() {
        return t;
    }
    inline const Test &getTest() const {
        return t;
    }
}

Which member function gets called if we have following code?

Foo foo;  // suppose foo has been initialized
Test& t1 = foo.getTest();
const Test& t2 = foo.getTest();
like image 870
Sunshine Avatar asked Sep 08 '16 21:09

Sunshine


2 Answers

no, it is not valid, but in your example it is, because the last const is actually part of the signature (the hidden Foo *this first parameter is now const Foo *this).

It is used to access in read-only (get const reference, the method is constant), or write (get non-const reference, the method is not constant)

it's still a good design choice to return the reference of the same entity (constant or non-constant) in both methods of course!

like image 116
Jean-François Fabre Avatar answered Nov 08 '22 18:11

Jean-François Fabre


No.

You cannot overload on return type.

Why? The standard says so.

And it actually makes sense - you can't determine what function to call in all situations.

like image 37
Jesper Juhl Avatar answered Nov 08 '22 20:11

Jesper Juhl