0
Compiler: MSVC

So I am trying to implement my own number system that can store infinite numbers in C++. What I did was overload operator<< for my custom class BigInt as such:

inline std::ostream& operator<<(std::ostream& os, BigInt& bint)
{
    os << bint.num; // num is a std::string
    return os;
}

Now I implemented addition for my custom numbers:

inline BigInt& operator+(BigInt& bint1, BigInt& bint2)
{
    BigInt sum;

    // addition code...

    return sum;
}

Now when I try to print a BigInt like this:

BigInt bint1("123");
std::cout << bint1;

..it works. But nothing prints out when I do this:

BigInt bint1("123"), bint2("456");
std::cout << bint1 + bint2;

I suspect some sort of UB here. What am I doing wrong here?

The Coding Fox
  • 1,488
  • 1
  • 4
  • 18
  • 3
    You're correct that it's UB. But it's not in the `operator<<` function, it's in the `operator+` function where you return a reference to a local variable. You should return by value instead. – Some programmer dude May 20 '22 at 12:12
  • Does your C++ textbook have an explanation why returning a reference to an object that's declared local in a function, being returned from, is always wrong, and why? – Sam Varshavchik May 20 '22 at 12:12
  • Turn on your compiler warnings. Your compiler should have warned you about this particular bug in your code. – Eljay May 20 '22 at 12:48

0 Answers0