3

The code below works:

   #include <iostream>                                                             

   using namespace std;                                                            

   struct Formula {                                                                
     int x;                                                                   
   };                                                                              

   int main() {                                                                    
    Formula f = {1};                                                              
    return 0;                                                                     
  } 

However, after adding the default value for the member variable, it fails:

   #include <iostream>                                                             

   using namespace std;                                                            

   struct Formula {                                                                
     int x = 10; // Initialize x with a default value 10.                                                            
   };                                                                              

   int main() {                                                                    
    Formula f = {1}; // this line no longer works.                                                           
    return 0;                                                                     
  } 

The error is below:

g++ -std=gnu++11 exp07.cc 
exp07.cc: In function ‘int main()’:
exp07.cc:10:17: error: could not convert ‘{1}’ from ‘<brace-enclosed initializer list>’ to ‘Formula’
   Formula f = {1};
Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
cy77
  • 55
  • 5
  • 1
    In C++11 an in class member initializer makes a [class a non-aggregate](http://stackoverflow.com/q/27118535/1708801) ... in C++14 this is no longer the case. – Shafik Yaghmour Apr 15 '15 at 01:56

0 Answers0