Click here to Skip to main content
12,689,568 members (26,433 online)
Rate this:
Please Sign up or sign in to vote.
See more: C++

I have a class named Yup and it has one data member of type int(called number).
I have overloaded the cout and + operators.

cout<<object(type Yup)==> prints the number.
The object1+object2 adds the numbers of 2 objects.

In the main I have

Yup t(23),t1(27);

When I do this: Yup t2=t+t1; cout<<t2<<endl;==> I get 50;

When I do this: cout<<(t+t1)<<endl; ==> I get -87293...

How can i write it in one line?
How it is compiled?

ostream &operator<<( ostream &output, const Yup &num )
    return output;

Yup &operator+(const Yup &tr1,const Yup &tr2 )
    Yup k(0);
    return k;
Posted 25-Nov-12 3:29am
Updated 25-Nov-12 4:50am
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

Your operator+ overload[^] returns a reference to a local variable.

Remove the reference:
Yup operator+( const Yup &tr1,const Yup &tr2 )
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

You probably have defined operator+ incorrectly. It should return an object of your class that contains the result. If in doubt, show your code by using the "Improve question" button on your question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170113.4 | Last Updated 25 Nov 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100