+ 12

Why we can't initialize data member of class in c++?

25th Mar 2017, 8:36 AM
Nitin Dixit
Nitin Dixit - avatar
2 Antworten
+ 3
There are two way to initialize data member of a class. 1. Creating constructor function. It is a special function that is called at the time of object creation. Example: class Point{ int x; int y; public: //Default Constructor Point () { x=y=0; } //Overload Constructor with 1 parameter Point (int a) { x=y=a; } //Overload Constructor with 2 parameters Point (int a, int b) { x=a, y=b; } void show(){ cout<<x<<", "<<y; } }; int main (void){ Point p1, p2=9, p3(6,7); p1.show(); }
25th Mar 2017, 9:18 AM
देवेंद्र महाजन (Devender)
देवेंद्र महाजन (Devender) - avatar
+ 2
It is not the case that we can't initialise. We initialise it in the public section of the class using the default constructor (if you don't write one compiler will give it's own) which sets all the member variables to it's default value 0 and parameterized constructor which sets the member variables to the parameters of the constructor.
31st Mar 2017, 5:21 AM
Vishnu ks
Vishnu ks - avatar