Skip to main content
gamedev.net
🔒 Locked

Interesting const behavior

Started by daerid 3 replies 300+ views
Original Post
daerid
daerid

  
struct test
{
	test( int& ref ) : i( ref ) {}

	int& i;
};

int main( int argc, char** argv ) {
	
	int i = 0;
	test t( i );

	const test& tr = t;

	tr.i = 4;

	return 0;
}
  
Why does that compile and work? I was under the impression that when an object/reference is defined as const, it''s members are treated as const (i.e: the int& i in struct test would be treated as const int& i). I''d like to understand this, if anybody''s got a reference from the standard that explains it, I''d be most appreciative. Thanks
daerid@gmail.com
JohnBolton
JohnBolton
quote:
Original post by daerid
...
I was under the impression that when an object/reference is defined as const, it''s members are treated as const...



Yes, but tr.i is a reference to a non-const. You can''t change tr, and you can''t change test::i, but you can change the value that tr.i references.

Effectively,

tr.i = 4;

is the same as

i = 4;
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
daerid
daerid
Huh... ok. That clears it up. Thanks a lot guys
daerid@gmail.com

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.