0

Hi all,

Please answer this question. Why the output is ACA??
In the line obj = obj+6; the 6 should have been converted to obj type but, why it is converting the obj to int type?
Please help...

#include <iostream>

using namespace std;

class Base {
public:
    Base(int m_var=1):i(m_var){
        cout<<"A";
    }
    Base(Base& Base){
        cout<<"B";
        i=Base.i;
    }
    operator int() {
        cout<<"C";
        return i;
    }
    int operator+(Base& Base)
    {
        cout<<"D";
        return i+Base.i;
    }
private:
    int i;
};

int main()
{
    Base obj;
    obj = obj+6;
    return 0;
}

Edited by pritaeas: Moved.

2
Contributors
1
Reply
19
Views
3 Years
Discussion Span
Last Post by Lucaci Andrew
1

For a better understanding of this output, I suggest this code to run in the main() function:

int main()
{
    Base obj;
    cout<<" 1st - initialization.\n";
    int b = obj+6;
    cout<<" 2nd - get the int via the int() conversion operator\n";
    obj = b;
    cout<<" 3rd - create a new object";
    return 0;
}

In your class you have implemented the conversion operator int(). By this, you can use the current class like the class int, that is, whenever the class is used in a context where a number (say an int) must be used, it will behave like actually using an int. I'll link the original post, since he explains better than I do:
Click Here

Edited by Lucaci Andrew

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.