2

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?

Dennis
  • 7,907
  • 11
  • 65
  • 115
  • There have been two huge language changes since VC6. But I've no idea whether it follows standard pre-1998 rules, or its own, since I'm not quite old enough to have used C++ before 1998. The first version is definitely wrong since at least C++98. – Mike Seymour Nov 06 '14 at 16:52
  • Any reason you aren't using an [initialization list](http://www.cprogramming.com/tutorial/initialization-lists-c++.html)? @Mgetz that doesn't apply here, you got the terms backwards – clcto Nov 06 '14 at 16:56

2 Answers2

8

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.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • I am pretty sure I didn't use initialization lists, that's something of a "more advanced" syntax that I didn't learn until later. But It is possible that I forgot exactly what I did, namely, quite possibly I was actually using `this->` and maybe my confusion was around being able to use the same variable name for `this->x` and `x`, without having to use `_x` or a another differently-named variable from the class member var – Dennis Nov 06 '14 at 17:37
2

Or this.

class foobar {
public:
    foobar(int x, int y) : x(x), y(y)
    {
    }

private:
    int x, y;
};
Surt
  • 15,501
  • 3
  • 23
  • 39