I've been programming in C++ for a few years now. I'm not intimate with the standard per se, but I understand, for the most part, how things work.
I've hit a problem that simply has me perplexed.
Create the following class.
class Test {
public:
int _i;
double &_d;
Test(int i, double d) : _i(i), _d(d) { }
};
Now, inside main(), do the following:
void main()
{
double d1(3.0), d2(4.0);
Test t1(3, d1);
Test t2(4, d2);
t2._d = 5.0;
}
When I run this simple program in debug mode, an interesting this occurs. After t2 is instantiated, the "_d" member variable of both t1 AND t2 is equal to 4.0. After executing the direct assignment to "t2._d", the "_d" member variable of both t1 AND t2 is equal to 5.0. Why!!!!?
I'm using Visual C++.NET to run this, but I've seen the same result on a old copy of Visual C++ 6.0. Is this correct?
If I inspect the memory of t1 and t2, this is what I see:
t1: 03 00 00 00 c8 fd 12 00
t2: 04 00 00 00 c8 fd 12 00
So the "_i" member variable is behaving as expected, but the "_d" member variable appears to be behaving like a static member variable, i.e., class-scoped or shared among both objects.
I've been working a lot lately, so my brain may just be tired or incapable of thinking clearly right now. But this seems incorrect to me. Can someone help me!?
I've hit a problem that simply has me perplexed.
Create the following class.
class Test {
public:
int _i;
double &_d;
Test(int i, double d) : _i(i), _d(d) { }
};
Now, inside main(), do the following:
void main()
{
double d1(3.0), d2(4.0);
Test t1(3, d1);
Test t2(4, d2);
t2._d = 5.0;
}
When I run this simple program in debug mode, an interesting this occurs. After t2 is instantiated, the "_d" member variable of both t1 AND t2 is equal to 4.0. After executing the direct assignment to "t2._d", the "_d" member variable of both t1 AND t2 is equal to 5.0. Why!!!!?
I'm using Visual C++.NET to run this, but I've seen the same result on a old copy of Visual C++ 6.0. Is this correct?
If I inspect the memory of t1 and t2, this is what I see:
t1: 03 00 00 00 c8 fd 12 00
t2: 04 00 00 00 c8 fd 12 00
So the "_i" member variable is behaving as expected, but the "_d" member variable appears to be behaving like a static member variable, i.e., class-scoped or shared among both objects.
I've been working a lot lately, so my brain may just be tired or incapable of thinking clearly right now. But this seems incorrect to me. Can someone help me!?