-3

To the down-voters: I understand that this was a poorly constructed question. If you'll scroll down to the answers, you'll see that I discovered the source of the problem. While the question itself might not be helpful, I hope the answer will help somebody experiencing similar trouble with operator overloading. The problem was what it was; I cannot identify any edits or revisions that would make this a better question. Therefore, if you're going to submit a down-vote, please add a constructive comment as well. Thank you.


I'm running the following code

myObject o = myObject();
cout << o << endl;

My (friend) << operator is overloaded here:

ostream& operator << (ostream& s, myObject o)
{
    s << doStuff(o, s) << endl;
    return s;
}

Expected output:

object contents

Actual output is, for some reason, including the memory address:

5452ED48object contents

Why?

Peter
  • 4,021
  • 5
  • 37
  • 58
  • 3
    What is `doStuff()`? By the way. Knock of all that "myObject o = myObject();" business. "myObject o;" is sufficient. – Benjamin Lindley Apr 15 '12 at 02:10
  • @BenjaminLindley: `myObject o` may not be sufficient if `myObject` is POD. – Nawaz Apr 15 '12 at 02:12
  • 1
    Not sufficient information, voting for closing. – Nawaz Apr 15 '12 at 02:15
  • 2
    It is usually a questionable practice to write endl inside your << operator: if the caller wants a new line, he'll add a new line (like you did). – Sergey Kalinichenko Apr 15 '12 at 02:16
  • `.doStuff()` is a recursive function to traverse a tree. I didn't think it was relevant because the error appeared before I added the method. I thought my problem might have a more general solution. Perhaps I was wrong. I will try to get an edit up soon. – Peter Apr 15 '12 at 02:19

2 Answers2

0

We cannot understand what you wanna do... I understood something like this:

#include <iostream>
using namespace std;

class obj{

    friend ostream&operator<<(ostream &out, const obj o);
public:
    obj(int a);
    int change_data();
private: 
    int s;
    int d;

};

obj::obj(int a)
{
    s = a;
    d = s;
}

int obj::change_data()
{
    return 99;
}

ostream&operator<<(ostream &out, const obj o){
    out << o.s;
    out << " ";
    out << o.d;
}

int main(int argc, char **argv) {
    obj some(1);
    cout << some;
    return 0;
}

Output:

1 1

It seems to you have to learn about passing values by reference, because when you use the "<< "operator overloading you do not return any value, you return values in the argument.

0

Sorry for not providing enough detail. It turned out that I should have done this:

doStuff(o, s);
return s;

Apparently I was appending the desired output to s, which already contained the address.

Peter
  • 4,021
  • 5
  • 37
  • 58