Alcott
Alcott

Reputation: 18585

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 As 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?

Upvotes: 47

Views: 19160

Answers (5)

John Duffy
John Duffy

Reputation: 334

Yes, for example see the std::streambuf pointers:

protected:
   char* pbase() const;
   char* pptr() const;
   char* epptr() const;

http://en.cppreference.com/w/cpp/io/basic_streambuf/pptr

Upvotes: 1

visitor
visitor

Reputation: 1801

It does not open a door to modifying _px but rather what _px points to. It's up to you to decide whether you want to allow this or not.

For example, an iterator::operator-> would return a non-const pointer and const_iterator::operator-> would return a const pointer. Both methods can be const themselves.

Upvotes: 5

sbi
sbi

Reputation: 224049

Yes, for your case it can. However, it's generally advised to not to do this, because it allows changing constant objects:

void f(const A& a) 
{
  *(a.foo()) = 42; // damn!
}

Upvotes: 3

Alok Save
Alok Save

Reputation: 206518

int *_px becomes int *const _px inside a const member function this implies that the pointer cannot be reseated but the data pointed to is still modifyable. Further your function returns a copy of the pointer so it does not matter anyways.

Upvotes: 5

Mike Seymour
Mike Seymour

Reputation: 254431

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;}

Upvotes: 43

Related Questions