-11

Check the following code:

#include<iostream>
using namespace std;

class example
{
    public:
    int number;

    example()
    {
        cout<<"1";
        number = 1;
    }

    example(int value)
    {
        cout<<"2";
        number = value;
    }

    int getNumber()
    {
        cout<<"3";
        return number;
    }
};

int main()
{
    example e;
    e = 10;
    cout<<e.getNumber();
    return 0;
}

What is the output of the above code. Also, I want to know what happens when an object is directly assigned to a value. How will the compiler interpret it?

1 Answers1

0

first you typed

example e;

So first constructor called and 1 printed

example()
{
    cout<<"1";
    number = 1;
}

output :

1

then you typed : e=10 its equal to e = example(10); so another constructor called :

example(int value) /// beacause you used example(10)
{
    cout<<"2";
    number = value;
}

so your output is :

12

and number is 2 Finally in :

cout<<e.getNumber();


3 is couted but in the other hand value is `10`    

because number = value your number is 10
So in Finally your output is :

12310

thanx for @StoryTeller for editting explaintions

keyvan vafaee
  • 464
  • 4
  • 15