James Machin James Machin -4 years ago 72
C++ Question

Why is it not possible to assign a variable in the class body?

I'm not sure I've phrased the question very well as I'm new to c++, but I was wondering why, in the following code, can the variable

xyz
be assigned like this

class Fraction {
public:
int num, denom;
int xyz = 0;

// Constructors
Fraction() {
num = 0;
denom = 1;
}

Fraction(int n, int d) {
num = n;
denom = d;
}


};


but if written like this

class Fraction {
public:
int num, denom;
int xyz;
xyz = 0;

// Constructors
Fraction() {
num = 0;
denom = 1;
}

Fraction(int n, int d) {
num = n;
denom = d;
}


};


returns errors on compilation, namely:

error: C2059: syntax error: '='


and

error: C2238: unexpected token(s) preceding ';'

Answer Source

xyz = 0 is an expression. Ordinary expressions like your xyz = 0 can only appear in initializers and in statements. And statements are basically the primary example of executable code in C++ language. In C++ language executable code (i.e. statements) is supposed to be written inside functions. That's just how the language works.

So, in your case the only way to somehow "plant" your expression outside of a function is to use it in an initializer. For example you can do something like this

struct S
{
    int a;
    int b = (a = 42);
};

But this trick is ugly and ill-advised.

Your first syntax is initialization syntax. The = symbol is not an assignment operator, but rather just a syntactic element of initializer syntax. Even in this case the actual initializtion will become a part of constructor code. So, even that code will end up being a part of a function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download