There's something I don't understand about classes. I mean, when I declare a class type which contains a member whose value rely on other members within the class, i.e.:
1 2 3 4 5
|
class foo
{ public:
int a,b;
int x=a+b;
} obj;
|
, it pops up the following errors:
1.C:\Users\Andreutza\Desktop\xfjkfxfxkj\main.cpp|6|error: 'foo::a' cannot appear in a constant-expression|
C:\Users\Andreutza\Desktop\xfjkfxfxkj\main.cpp|6|error: 'foo::b' cannot appear in a constant-expression|
C:\Users\Andreutza\Desktop\xfjkfxfxkj\main.cpp|6|error: ISO C++ forbids initialization of member 'x'|
C:\Users\Andreutza\Desktop\xfjkfxfxkj\main.cpp|6|error: making 'x' static|
C:\Users\Andreutza\Desktop\xfjkfxfxkj\main.cpp|6|error: ISO C++ forbids in-class initialization of non-const static member 'x'|
C:\Users\Andreutza\Desktop\xfjkfxfxkj\main.cpp||In function 'int main()':|
C:\Users\Andreutza\Desktop\xfjkfxfxkj\main.cpp|12|error: 'class foo' has no member named 'sum'|
--------------------------------------------------
But when I put in something like this:
1 2 3 4 5 6 7 8
|
class foo
{ public:
int a,b;
int sum(void)
{
return a+b;
}
} obj;
|
, it gives me no error.
And I don't understand why. I mean, in the second example it's also a kind of assignment but between a function and a value returned by the sum of those variables, and as that function can take any value it means that it acts just like a variable , so I don't get the difference. It's like in the second example the function definition is jumped over until the compiler gets in the context of an object of that class, unlike the first example. So why is this happening? Thanks in advance!