Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why primitive to class type conversion destroys object values?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading