Reputation: 985
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;
}
Upvotes: 17
Views: 18720
Reputation: 1801
Nawaz's answer is very good. However, the point about the compiler catching the error need not always hold. The C++ FAQ warns about it here.
The good news is that the compiler will often catch you if you get this wrong. In particular, if you accidentally return a member of your this object by non-const reference [...] the compiler will often detect it and give you a compile-time error [...].
The bad news is that the compiler won’t always catch you: there are some cases where the compiler simply won’t ever give you a compile-time error message.
Translation: you need to think. If that scares you, find another line of work; “think” is not a four-letter word.
Upvotes: 0
Reputation: 361322
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!.
Upvotes: 37
Reputation: 503805
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.
Upvotes: 7