about operator overloading


when i run this i get the following error: cannot overload functions distinguished by return type alone.


Book& operator + (const Book& b1, const Book& b2) {
Book b3;
b3.author_ = b1.author_ + b2.author_;
b3.isbn_ = b1.isbn_ + b2.isbn_;
b3.price_ = b1.price_ + b2.price_;
b3.title_ = b3.title_ + b3.title_;
return b3;
}


however when i remove the reference sign infront of books it works ?


Book operator + (const Book& b1, const Book& b2) {
Book b3;
b3.author_ = b1.author_ + b2.author_;
b3.isbn_ = b1.isbn_ + b2.isbn_;
b3.price_ = b1.price_ + b2.price_;
b3.title_ = b3.title_ + b3.title_;
return b3;
}
Not exactly sure what the compiler is trying to say there, but your first operator overload (with Book& return value) is just plain wrong, because you are trying to return a local object by reference, which means you're returning garbage.

Why? Book b3 only exists inside the scope of your operator function. It is popped off the stack once the function returns, and your returned Book reference now refers to an invalid value that no longer exists. It's undefined behavior to use it.

Your second operator overload looks correct.

Edit: Except
b3.title_ = b3.title_ + b3.title_;
???
Last edited on
Topic archived. No new replies allowed.