I recall I used to be able to do this and have it work as intended:
class foobar
{
public:
foobar(int x, int y)
{
x = x; //the variables x, y belonging to the class got correctly initialized
y = y;
}
private:
int x, y;
};
The above worked in circa 200x on Microsoft Visual C++ 6.0 and some later versions, I believe.
But now I have to do this on Microsoft Studio 2013 and I have to use this->, as such:
class foobar
{
public:
foobar(int x, int y)
{
this->x = x; //the other way no longer initializes class vars
this->y = y;
}
private:
int x, y;
};
Was there a language spec change or Microsoft compiler change?
Perhaps you are thinking instead of initializer list syntax, which would be unambiguous and should work correctly on any (non-buggy) C++ compiler:
foobar(int x, int y) : x(x), y(y) { }
In this case, the x and y before the parens are unambiguously data members, because that's the only thing that can go there (besides constructors for parent types). Inside the parens, the x and y refer to the constructor arguments that shadow the data members.
I can't think of any circumstance under which x = x; would do anything other than no-op self-assignment (buggy user-defined assignment operator overloads aside). If this worked in a prior VC++ version then it would have been a VC++ compiler bug. More likely, you used to use initializer list syntax (which does work) and forgot that's what you did.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With