+ 9

Initialisation of data members

Why the data members of classes can not be initialised at the time of their declaration in c++?

7th May 2017, 6:55 AM
Jain Rishav Amit
Jain Rishav Amit - avatar
4 Antworten
+ 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.
7th May 2017, 8:05 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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 }
7th May 2017, 8:06 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
+ 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 }
7th May 2017, 4:08 PM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
+ 1
To be correct, it IS VALID since C++11. A C++11 compiler will happily accept definition in class scope.
7th May 2017, 11:16 AM
Norbivar
Norbivar - avatar