prehistoricpenguin
prehistoricpenguin

Reputation: 6326

Default value for struct member in c++

It seems that we can not give a default value for struct members in c++,but I find that code as below can compile and run, why? Am I missing something?

struct Type {
    int i = 0xffff;
};

Program:

#include <iostream>

using namespace std;
struct Type {
    int i = 0xffff;
};
int main() {
    // your code goes here
    Type val;
    std::cout << val.i << std::endl; 
    return 0;
}

Upvotes: 0

Views: 1808

Answers (2)

Germ&#225;n Diago
Germ&#225;n Diago

Reputation: 7663

It is going to depend on the compiler you use.

For gcc and clang you need to pass the flag -std=c++11 to the compiler.

Support for member initializer and other c++11 features:

  • gcc since 4.7. See here.
  • clang since 3.0. See here.
  • Visual studio compiler in its 2013 version. See here.

Upvotes: 1

Mantosh Kumar
Mantosh Kumar

Reputation: 5731

This is correct and introduced in C++11 standard. This concept is known as in-class member initializer

You can check Stroustrup FAQ link on this concept:

http://www.stroustrup.com/C++11FAQ.html#member-init

Upvotes: 0

Related Questions