Re: References
On 2010-11-11 14:14:07 -0500, Andrea Crotti said:
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?
Do I need a "void setX(const int& _x)" in Packer then otherwise?
It calls the constructor of Packer. But look at the argument that it
passes: _x is the argument to Packet's constructor. It has the value 10
when Packet's constructor runs, and Packer's constructor stores a
reference to that argument. Once Packet's constructor returns, that
argument doesn't exist any more, and the reference points to nowhere.
As Leigh said, the code should use p(x), to initialize the Packer
object so that it's reference points to the value stored in Packet and
not the the argument passed to the constructor.
By the way, this is very difficult to talk about when everything is named x.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)