3

Im trying to overload the operator<<

const ostream & operator<<(const ostream& out, const animal& rhs){
    out << rhs.a;
    return out;
}

it seems that im getting an error because im return a const and also because the first argument is const refrence to an ostream object.

cout << objectOfAnimal1 << objectOfAnimal2 ;

it work just fine if I change the the return type and the operator signature to this one:

ostream & operator<<(ostream& out, const animal& rhs)
4
  • 1
    You are trying to write data into the ostream, that's not a very const operation! Commented May 3, 2012 at 15:46
  • @FatalError can you tell where Im modidying the object Commented May 3, 2012 at 15:49
  • const means the object won't be modified; when you write cout << objectofanimal1 you are writing to the ostream that you marked as const. the compiler is smart enough to know that it can't be const Commented May 3, 2012 at 15:53
  • A specific question would have helped this post. We can all infer the question, but I suspect we will all infer slightly different questions. Commented May 3, 2012 at 16:11

2 Answers 2

4

You need to have:

ostream & operator<<(ostream& out, const animal& rhs)

In your code You are trying to modify a const ostream object, and so you get the errors.
It should not be const.

Sign up to request clarification or add additional context in comments.

7 Comments

yes I know that will work, but why when I change it const it wont work. thanks
@AlexDan: The point is, it cannot be const! because you are modifying the object state.
Im not changing anything about the ostream object
@AlexDan: Yes you are. You are streaming rhs.a into it (in the expression out << rhs.a).
@AlexDan: you're feeding stream with data; when you eat a lot of donuts, you're getting fat, hence going through changes. No const, no const at all.
|
1
ostream & operator<<(ostream& out, const animal& rhs){
out << rhs.a;
return out;
}

You've already explained what is probable reason of problem and you really didn't try it out?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.