0

So I have test.h which contains:

#ifndef TEST_H_
#define TEST_H_

class test {
public:
    int value;
};

#endif /* TEST_H_ */

and my main.cpp:

#include "test.h"

class Magic {
    test x;
    x.value = 2; // Syntax error
};

int main () {
    test y;
    y.value = 2; // Works fine

    return 0;
}

Why is this happening?

  • 1
    You cant put arbitrary code like this in a class declaration. That's how the language is defined. – Borgleader Nov 30 '16 at 12:55
  • 2
    What book/tutorial are you learning from that has code written like this? – Cody Gray - on strike Nov 30 '16 at 12:57
  • So to use `test` I have to be in the main function? – SomeoneWithAQuestion Nov 30 '16 at 12:57
  • You need to get a book on the basics of C++. You can use test in a class but it needs to be inside a function of some sort. – Borgleader Nov 30 '16 at 12:59
  • @CodyGray was just trying some things out. Great help by the way. – SomeoneWithAQuestion Nov 30 '16 at 13:04
  • 2
    I wasn't trying to be mean. Two things: (1) There are actually really bad C++ books/tutorials out there, and I wouldn't be completely shocked if you replied with a link to one of them that had code like this somewhere. (2) Trying things out is a rather frustrating and unproductive way to learn a programming language. I highly recommend getting [a book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) that can help teach you and answer some of the simpler questions before you have to ask them. – Cody Gray - on strike Nov 30 '16 at 13:13

1 Answers1

3

Assigning values like that is not valid syntax in a class definition in c++. The error has nothing to do with headers or whatever. Try putting everything in a single file and you will see the same behavior.

If you want to have default initialization of x.value to 2 for each instance of Magic define this in the constructor of Magic:

class Magic {
  test x;
  Magic() {
    x.value = 2;
  }
};
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176