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;
}

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.