Home > Net >  Constructor invocation in C
Constructor invocation in C

Time:11-10

I tried to find out the output of this program in C .

#include<iostream>
using namespace std;

class MyInt {
    int i;
    public:
        MyInt() {
            cout<<1;
            i = 0;
        }
        MyInt(int i) {
            cout<<2;
            this->i = i;
        }
        int value(){
            return i;
        }
};

int main() {
    MyInt i;
    i = 10;
    cout<<i.value();
} 

I expected the output to be 210 but the output of the program is 1210. So why are both the default constructor and parameterized constructor invoked in this case?

CodePudding user response:

If you want to print 210 you should write:

MyInt i = 10;
std::cout << i.value();

MyInt i; calls the default constructor. That is why you are printing 1 first.

CodePudding user response:

MyInt i;

The above line invokes MyInt::MyInt(), creating an object and outputting 1.

i = 10;

The above line invokes MyInt::MyInt(int i), creating another object and outputting 2. The second object is then assigned to the first object, which outputs nothing.

cout<<i.value();

The above line invokes MyInt::value(), outputting 10.

  • Related