Alcott Alcott - 1 month ago 6
C++ Question

Can const member function return a non-const pointer to a data member?

Code goes first:

class A
{
public:
...
int *foo() const
{
return _px;
}
private:
int *_px;
}


The member function
foo
returns a non-const pointer to
private
member
_px
, which, I think, opens a door to modifying member
_px
, right?

Is
foo
a
const
member function? Should I add a
const
in front of the return type?

UPDATE

What a const-member-function should guarantee is that, it cannot change any data-member, right?

In my case, function
foo
doesn't open a door to modifying
class A
s data-member
_px
, but a door to modifying what
_px
pointing to, So my question is, does this violate what a const-function should guarantee?

Answer

A const member function can only return a const pointer or reference to a member.

However, your example isn't returning a pointer to a member; it's returning a copy of a member that happens to be a pointer. That is allowed in a const member function (even if the pointer happens to point to another member).

This would not be allowed (note that it's now returning a reference):

int *& foo() const {return _px;}

but this would (returning a const reference):

int * const & foo() const {return _px;}
Comments