vrajen1
vrajen1

Reputation: 41

C++::global Operator Overloading Issue

Scenario 1

enum number{num=3};
int& operator+(const int& i1,number& n2)
{
    return (i1*10 + n2);
}
int main()
{
    int a,b=7;
    number n1 = num;
    a=7+n1;
}

The output is program crashes with stack overflow......Why does stack overflow happen ??int& operator+(const int& i1,number& n2) ....all args and return type are reference only...then why stack overflow

Scenario 2

enum number{num=3};
int operator+( int& i1,number& n2)
{
    return (i1*10 + n2);
}
int main()
{
    int a,b=7;
    number n1 = num;
    a=b+n1;
}

I get proper output with 73.

Scenario 3

 int operator+(int i1,number n2)
    {
        return (i1*10 + n2);
    }
    int main()
    {
        int a,b=7;
        number n1 = num;
        a=b + n1;
    }

Scenario 3 also leads to Stack overflow Is there copy constructor for an int object??

Upvotes: 1

Views: 462

Answers (2)

Bathsheba
Bathsheba

Reputation: 234725

Scenario 1 is returning a dangling reference. The program behaviour is undefined. The stack overflow should be viewed as a manifestation of this behaviour.

Scenario 2 is well-formed as it is returning a value copy of the result. But you should change the prototype to int operator+(const int& i1, const number& n2) or even int operator+(const int i1, const number n2), and then make adjustments to the function body to avoid the function calling itself (an anonymous temporary will bind to a constant reference); the easiest way would be to either cast the enum to an int or use the contrivance

return i1 * 10 - -n2;

although you would be back to square one if you implemented a global subtraction operator!

Upvotes: 1

TartanLlama
TartanLlama

Reputation: 65620

In Scenario 1, you get a stack overflow because you are repeatedly calling the same function recursively.

int& operator+(const int& i1,number& n2)
{
    return (i1*10 + n2);
}//         ^^^^^

The marked expression creates a temporary int, which can bind to a const int&, so operator+(const int&, number&) is called.

Scenario 2 works because i1*10 cannot bind to a non-const int&, so n2 is implicitly converted to an int and the standard int addition operator is called.

Upvotes: 4

Related Questions