Returning non-const reference from a const member function
Why does returning the reference to a pointed-to member variable work, but not the other? I know that a const
member function should only return const
references, but why does that not seem true for pointers?
class MyClass
{
private:
int * a;
int b;
public:
MyClass() { a = new int; }
~MyClass() { delete a; }
int & geta(void) const { return *a; } // good?
int & getb(void) const { return b; } // obviously bad
};
int main(void)
{
MyClass m;
m.geta() = 5; //works????
m.getb() = 7; //doesn't compile
return 0;
}
Solution 1:
int & geta(void) const { return *a; } // good?
int & getb(void) const { return b; } // obviously bad
In a const-function, every data member becomes const in such way that it cannot be modified. int
becomes const int
, int *
becomes int * const
, and so on.
Since the type of a
in your first function becomes int * const
, as opposed to const int *
, so you can change the data (which is modifiable):
m.geta() = 5; //works, as the data is modifiable
Difference between : const int*
and int * const
.
-
const int*
means the pointer is non-const, but the data the pointer points to is const. -
int * const
means the pointer is const, but the data the pointer points to is non-const.
Your second function tries to return const int &
, since the type of b
become const int
. But you've mentioned the actual return type in your code as int &
, so this function would not even compile (see this), irrespective of what you do in main()
, because the return type doesn't match. Here is the fix:
const int & getb(void) const { return b; }
Now it compiles fine!.
Solution 2:
Because a
becomes int * const a;
. That is, you cannot change the value of a
(change what it points at), just as const
says. The const-ness of what a
points at is a completely different issue.
Please see my answer here for a thorough discussion of const and const member functions.