简体   繁体   中英

Why we cannot initialize the member variable of a class in C++

It's giving error:

#include <iostream>
using std::cout;

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

public:
    void display();
};

int main()
{
    // ...
}

(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.

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
    { }
};

In the class, we usually declare all the variables in private section. And we do not initialize them in the class. You can use the constructor in order to initialize them.

class stud {

private:

    int a;

public:

    stud();
};

stud::stud() 
{

int a = 5; // initialize here..

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM