+ 12
Why we can't initialize data member of class in c++?
2 Respostas
+ 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();
}
+ 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.