Re: References
On 11/11/2010 2:14 PM, Andrea Crotti wrote:
Ian Collins<ian-news@hotmail.com> writes:
Packer is initialises with the constant 10, not Packet.x.
A moment I don't get it now is
class Packer
{
public:
Packer(int& _x) : x(_x) {}
int& x;
void packData(char *);
};
class Packet
{
public:
int x;
Packer p;
Packet(int _x) : x(_x), p(_x) {}
};
int main() {
Packet p1(10);
cout<< p1.p.x<< endl;
p1.x = 3;
cout<< p1.p.x<< endl;
return 0;
}
but should not here in the constructor
Packet(int _x) : x(_x), p(_x) {}
call the constructor of Packer to set the value inside?
For a very short time (while the Packet constructor is running) the
reference inside the Packet::p member actually refers to a valid object
(the argument to the constructor of the Packet object). As soon as the
constructor returns, the temporary (the argument) is no more, and the
reference inside the 'p' member becomes invalid. Your program has
undefined behavior if it tries to refer to 'p1.p.x' after 'p1' has been
constructed.
Do I need a "void setX(const int& _x)" in Packer then otherwise?
No, you need to understand what a reference is.
V
--
I do not respond to top-posted replies, please don't ask