Unhandled exception when overloading << operator

0

I am trying to overload the << operator for a New Integer class that detects overflow of operations and below are my parts of codes:

    class NewInteger{
                private: 
                int num;

                public: 
                NewInteger();
                NewInteger(int);
                friend std::ostream &operator <<(std::ostream& out, const NewInteger& rhs);
                NewInteger operator+ (NewInteger);

                .../ many other member functions/
            }

Implementations are:

    NewInteger NewInteger::operator+(NewInteger n)
{
    int a = this->getValue();
    int b = n.getValue();
    if (a > 0 && b > max - a) {
        throw std::exception();
        std::cout << "studpid" << std::endl;
    }
    if (a < 0 && b < min - a) {
        throw std::exception();
    }

    return NewInteger(a + b);
}
  std::ostream & operator<<(std::ostream & out, const NewInteger& rhs)
    {
        out << rhs;
        return out;
    }

In the main.cpp, I try to test the code by running:

    NewInteger n7(4);
    NewInteger n8(5);
    std::cout << n7.operator+(n8) << std::endl;

The code builds fine and when I run it on Visual Studio 2015, it causes the program to close without giving a fatal error. So when I debug the code, it gives me: `

Exception thrown at 0x00C43B49 in NewInteger.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00192F90)

and the break point appears right at the implementation of operator<<. But I cannot figure out what exception I should try to catch at the implementation.

Can somebody please tell me what is the cause of this?

c++
operator-overloading
asked on Stack Overflow Apr 17, 2017 by dezdichado • edited Apr 17, 2017 by dezdichado

1 Answer

4
std::ostream & operator<<(std::ostream & out, const NewInteger& rhs)
{
    out << rhs;
    return out;
}

The first line calls operator<< on out and rhs -- which is the function you're defining. You have infinite recursion.

answered on Stack Overflow Apr 17, 2017 by aschepler

User contributions licensed under CC BY-SA 3.0