g3d
g3d

Reputation: 451

Using operator<< with const object

I have a trouble with overloading operator<< for const objects.I couldnt find out the problem

#include <iostream>
using namespace std;
class T
{
    friend ostream& operator<<(ostream& os,T& t)
    {
        os << "Val : " << t.value << endl;
        return os;
    }
private:
    int value;
public:
    T(int v) { value=v; }
    int getValue() const { return value; }
};

int main()
{
    const T t(2);
    cout << t;
    return 0;
}

Compiler Message:

error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const T' (or there is no acceptable conversion)

Upvotes: 0

Views: 146

Answers (4)

Code-Apprentice
Code-Apprentice

Reputation: 83537

Your operator<<() doesn't work with a const object because you have declared it as

friend ostream& operator<<(ostream& os,T& t)

You need to tell the compiler that you want to be able to use it with const objects:

friend ostream& operator<<(ostream& os, const T& t)

Upvotes: 2

meyumer
meyumer

Reputation: 5064

Make the T& a const reference in line:

friend ostream& operator<<(ostream& os,T& t)

So it becomes:

friend ostream& operator<<(ostream& os,const T& t)

Or, get rid of the &:

friend ostream& operator<<(ostream& os,T t)

Both will give the following result with your code:

Val : 2

in the console.

Upvotes: 0

Cyrille
Cyrille

Reputation: 14523

Just add a const and it should work :

friend ostream& operator<<(ostream& os,const T& t)

Upvotes: 0

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

Your operator<< should typically take its argument by const reference:

friend ostream& operator<<(ostream& os, const T& t)

A non-const reference cannot bind to a const object. This makes sense, otherwise you'd be able to modify the const object through the reference.

Upvotes: 1

Related Questions