return reference to member variable

B

Billy

Hi,

I would like to return a reference to a member variable:

class foo
{
int i;
int& geti() const;
};

int& foo::geti() const
{
return i;
}

But I get the following error:
invalid initialization of reference of type 'double&' from expression
of type 'const double'

Am I missing something? This seems like it should be doable.

-Billy
 
R

Rolf Magnus

Billy said:
Hi,

I would like to return a reference to a member variable:

class foo
{
int i;
int& geti() const;
};

int& foo::geti() const
{
return i;
}

But I get the following error:
invalid initialization of reference of type 'double&' from expression
of type 'const double'

Am I missing something?

Isn't that error message obvious? Your member function is const, and so
within it, i is const. You're trying to bind it to a non-const referernce,
which is of course not allowed. Make it:

const int& foo::geti() const
{
return i;
}
 
B

Billy

I was under the impression that making the function const meant:
"within this function I promise not to change the state of the object"

Since I wasn't changing the state of the object I thought it should be
ok. Clearly my understanding of making a function const was overly
naive.

Thanks, Billy
 
K

Karl Heinz Buchegger

Billy said:
I was under the impression that making the function const meant:
"within this function I promise not to change the state of the object"

Right.
But if you give away a reference to some object internals, then any
other lousy code *is* able to change the state of the object. Thus
the fact of handing out a reference opens the wormhole.
Since I wasn't changing the state of the object

You didn't. But you enabled other code to do it.
 
R

Rolf Magnus

Billy said:
I was under the impression that making the function const meant:
"within this function I promise not to change the state of the object"

"... and not to expose it in a way that makes changes to it from outside
possible".

Think of something like:

foo f;
f.geti()++;
 
B

Billy

Sorry I haven't done much programming...

Example
**********
foo f;
f.geti()++;

int& foo::geti(); // Example works
int& foo::geti() const; // Error, exposing foo via return
const int& foo::geti() const; // Error, f.geti() is const
const int& foo::geti(); // Error, f.geti() is const

Am I thinking about this right?

-Thanks, b
 

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
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top