Home > OS >  How to change the constructor initialization value in c and explain the reason?
How to change the constructor initialization value in c and explain the reason?

Time:12-01

using namespace std;


class Gparent{
    public:
    int house;
        Gparent(){
            house = 1;
            cout<<house<<endl;
        }
    ~Gparent(){
        cout<<"Gparent got killed"<<endl;
    }
};

class Parent: private Gparent{
    public:
        Parent(){
            Gparent::house=2;
            cout<<Gparent::house<<endl;
        }
    ~Parent(){
        cout<<"Parent got kiled"<<endl;
    }
};


int main(){
    Gparent g;
    g.house=100;
}

output: 1 Gparent got killed

why the output is not 100? I can understand the object creation but bit confused with the initialization part.Could someone help me to understand the concept?

CodePudding user response:

When you wrote Gparent g; this means

you are defining an object of type Gparent using the default constructor.

Now you have already provided a default constructor as :

Gparent(){
            house = 1;
            cout<<house<<endl;
        }

So the data member house is assigned a value of 1 and then you print that value using cout. Which is why you get the output 1 since house = 1 at this point.

Next when the object g is destroyed, the destructor is ran/executed and you get the output Gparent got killed.

So you didn't get the output 100 because the variable house had a value of 1 at the time of using cout.

Note if you use cout after the statement g.house = 100; you will see that its value is changed to 100 and hence 100 is printed on the console.

    Gparent g;
    g.house=100;
    cout << g.house<<endl;//THIS PRINTS 100 now because house = 100 at this point

CodePudding user response:

See what your code compiles to here. In the main(), this is what it roughly gets compiled to

call    Gparent::Gparent() [base object constructor]
:
mov     dword ptr [rbp - 8], 100
:
call    Gparent::~Gparent() [base object destructor]

It's basically just calling the constructor, so that'll print 1 since that's what house is initialized to and only after that the value of g.house is changed. And then the destructor is called so that'll print Gparent got killed. To see the changed value, you could perhaps change your code to

class Gparent{
    public:
    int house;
        Gparent(){
            house = 1;
            cout<<house<<endl;
        }
    ~Gparent(){
        cout<<house<<" Gparent got killed"<<endl;
    }
};

so that now the updated house member variable is printed during the destruction and you should get

1
100 Gparent got killed
  • Related