Why in the below code when I set c1 = 10 destroys all other values of variables (a, b, c) of the object. The statement should call the constructor and as the constructor is defined it sets the values of a to 10, but when I try to access values of b, c; it is giving me garbage values.
#include<iostream>
using namespace std;
class abc{
private:
// properties
int a,b, c;
public:
void setdata(int x,int y)
{
a = x;
b = y;
}
void showdata(){
cout << "a = " << a << " b = " << b << "\n";
}
// constructors
abc(){}
abc(int k)
{
a=k;
}
};
int main()
{
abc c1; // object intialization
c1.setdata(6,7); // setting values of properties
c1.showdata(); // printing values
c1 = 10; // primitive to class type conversion, constructor is being called
c1.showdata(); // why value of b and other variables is getting changed ?
return 0;
}
>Solution :
This is equivalent to
c1 = abc(10);
The constructor abc(int k) doesn’t initialize values b and c, therefore the member variables contain some random values. These random values, from the temporary abc(10) object, are then copied to c1.
The same is true for constructor abc(), here neither member variable is initialized, so they all contain "garbage" values. You will see this, when you call showdata right after construction
abc c1;
c1.showdata();