0

It's giving error:

#include <iostream>
using std::cout;

class stud
{
    int a = 0; // error??

public:
    void display();
};

int main()
{
    // ...
}
Azeem
  • 11,148
  • 4
  • 27
  • 40
Udesh
  • 11
  • 4
  • 4
    Use constructor to initialize that variable – Asesh Sep 01 '18 at 04:32
  • 9
    Welcome to Stack Overflow! What compiler are you using? In older versions of C++ (namely, C++03), that code won’t compile, but newer versions of C++ (C++11 and onward) should compile that just fine. – templatetypedef Sep 01 '18 at 04:36

2 Answers2

0

(The cause)

Non-static data member with a default member initializer is supported since C++11.

--

(The fix)

These days, many compilers support C++11.

For Visual Studio IDE users (like myself): On project properties: C/C++ > Language > C++ Language Standard: Set to C++11 or above. In Visual Studio 2017 C++11 is supported at baseline.

For other than Visual Studio IDE users, search the topic: "How to enable C++11" for your compiler.

Amit G.
  • 2,546
  • 2
  • 22
  • 30
0

It is possible to do this from C++11 onwards.

Through a default member initializer, which is simply a brace or equals initializer included in the member declaration, which is used if the member is omitted in the member initializer list.

class S
{
    int n = 7;
    std::string s{'a', 'b', 'c'};
    S() // copy-initializes n, list-initializes s
    { }
};
P.W
  • 26,289
  • 6
  • 39
  • 76