# C++ references and object lifetimes

## Recommended Posts

mongrol    118
Hi folks, A quick question on references and object lifetimes. I have one class that creates another then passes a reference to another object.
class Creature()
{
Weapon weapon;
}

If the Creature object is destroyed is the object it created also destroyed and the reference passed to GameWork is then invalid? I realise if I passed a pointer it would then be invalid and left hanging but what about references?

##### Share on other sites
jyk    2094
Quote:
 Original post by mongrolHi folks,A quick question on references and object lifetimes.I have one class that creates another then passes a reference to another object. class Creature(){ Weapon weapon; Gameworld.addWeapon(weapon&);}If the Creature object is destroyed is the object it created also destroyed and the reference passed to GameWork is then invalid?I realise if I passed a pointer it would then be invalid and left hanging but what about references?
Yes, references can become invalid under certain circumstances.

The exact scenario you have in mind isn't very clear though (for one thing, the bit of code you posted isn't valid C++). Can you possibly post an actual code example that demonstrates what you have in mind?

##### Share on other sites
imi    154
References work internally the same way as pointers. So they get invalid under the same circumstances.

Basically, references are "const pointer that are always initialized and never 0."

Ciao, Imi.

##### Share on other sites
mongrol    118
Thanks folks,
As usual my question was prompted by a design issue. I've been treating them as pointers which forced me to change my design a bit. Much tidier now.