-6
class Test {
public:
    int xyz=10;
};

Why does the compilation fail in c++?

jiafu
  • 6,338
  • 12
  • 49
  • 73
  • 2
    initialize it in constructor – Freak May 07 '13 at 03:50
  • 2
    In the future, if something fails to compile you'd likely also want to include the error the compiler gave you. – Kitsune May 07 '13 at 03:51
  • In addition to Kitsune's suggestion, don't ask us anything until you've googled the error message that the compiler gave you. Error messages are usually explained further in documentation. If you had just copy/pasted it into Google I'm sure you would have come across the answer much quicker than asking this question. Save yourself from counterproductivity, save the internet from pointless redundancy, and save us all from arthritis. That's similar to your role as a software developer, right? – autistic May 07 '13 at 03:56
  • 1
    [Compiles](https://ideone.com/OLvU9H) just fine for me. You're either using a compiler that doesn't support C++11's in-class initialization of data members, or you haven't set the right compiler flags while compiling your code. – Praetorian May 07 '13 at 04:00

3 Answers3

2

It's a new feature in C++11. compile your code with -std=c++11

richselian
  • 731
  • 4
  • 18
1

You should initialize members with a constructor. See this thread: in-class initialization of non-static and non-const members for good information.

Community
  • 1
  • 1
taocp
  • 23,276
  • 10
  • 49
  • 62
1

It is not a static member so initialize it in constructor.Non static member cannot be initialize without constructor
Also see this for further details about the initialization of static and non staic data

Despicable
  • 3,797
  • 3
  • 24
  • 42
  • This is no longer true, C++11 allows non-static data members to be initialized within the class definition. – Praetorian May 07 '13 at 04:02
  • yea true but this only shows error if someone is not using C++11.So here if he is getting the error it means that he is not using C++11 – Despicable May 07 '13 at 04:05
  • To quote the OP, the code *compile fail in c++*. None of us has any idea why it failed compilation :). But you're probably right that the OP is using a compiler that doesn't support this feature. – Praetorian May 07 '13 at 04:09