+ 9
Initialisation of data members
Why the data members of classes can not be initialised at the time of their declaration in c++?
4 Réponses
+ 12
Good question.
http://stackoverflow.com/questions/15451840/why-cant-we-initialize-class-members-at-their-declaration
tl;dr - Initialization applies to the object/instance of the class. During declaration, there is no object/instance of the class specified.
+ 6
Define constructor wrt the class to initialize data members of a class.
ex.
class demo {
int x;
int y;
public:
demo () {x=y=0;}
demo (int a){x=y=a;}
...
}
int main (void){
demo d1; // data members initialized with 0
}
+ 4
Following @Norbivar's point of view, cite example could be modified as
class demo {
int x=0;
int y=0;
public:
demo () {} //empty constructor
...
...
}
int main (void){
demo d1; // data members initialized with 0
}
+ 1
To be correct, it IS VALID since C++11. A C++11 compiler will happily accept definition in class scope.