Reference to private member...

B

barcaroller

Is it considered "acceptable" practice to return a const reference to
a private data member (something similar to string.c_str())?

class X
{
public:
const string& getString() const
{
return mystr;
}

private:
string mystr;
}


I know I'm breaking encapsulation but the other two options (below)
seem inefficient:

string getString() const
{
// copy constructor is invoked
return mystr;
}

... or ...

void getString(string& resString) const
{
// assignment operator is invoked
resString = mystr;
}
 
P

peter koch

Is it considered "acceptable" practice to return a const reference to
a private data member (something similar to string.c_str())?

Yes - this is fine.
    class X
    {
        public:
            const string& getString() const
            {
                return mystr;
            }

        private:
            string mystr;
    }

I know I'm breaking encapsulation but the other two options (below)
seem inefficient:

You're not breaking encapsulation. getString is part of your
interface, so there is no problem here.
[...]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,471
Messages
2,571,823
Members
48,797
Latest member
PeterSimpson
Top