First of all, you
can "overload" functions, i.e. you
can have
multiple member functions of the
same name.
But
only as long as they are
distinguishable by their parameters. Otherwise, as in your code, you'll get error:
overloaded function differs only by return type
Furthermore, you can
not return a
non-
const reference to a member variable from a
const member function!
int& get() const { return x; }
(
Within a
const member function
all member variables, except for
mutable, effectively become
const)
This results in:
1 2
|
error C2440: 'return': cannot convert from 'const int' to 'int &'
Conversion loses qualifiers
| |
Finally,
not declaring the following member function as
const, even though it returns a
const reference, doesn't make a whole lot of sense to me. There's
not really a reason why it shouldn't be a
const function:
const int& get() {return x;}
That's why your last functions makes more sense to me:
const int& get() const {return x;}
To make a long story short:
1 2 3 4 5
|
int get1() { return x; } // <-- return a "copy" of 'x' by value (okay)
int& get2() { return x; } // <-- return a mutable reference to 'x' (okay)
int& get3() const { return x; } // <-- return a mutable reference to 'x' from const function (error !!!)
const int& get4() { return x; } // <-- return a const reference to 'x' from a non-const function (possible though weird)
const int& get5() const { return x; } // <-- return a const reference to 'x' from a const function (okay)
| |