No operator found which takes a right hand operand of type 'B' (or there is no acceptable conversion)

I have the following piece of code. I'm trying to print the sum of two objects ints but the compiler gives me the following error:

binary '<<' : No operator found which takes a right-hand operand of type 'B' (or there is no acceptable conversion)

I don't really understand what the error means. Why does it say the operator << needs a type 'B'. Isn't there a sum of two ints?

#include <iostream>
using namespace std;

class A
{
    protected:
        int x;

    public:
        A(int i) :x(i) {}
        int get_x() {
            return x;
        }
};

class B : public A
{
    public:
        B(int i) :A(i) {}
        B operator+(const B& b) const {
            return x + b.x;
        }
};

int main()
{
    const B a(22), b(-12);
    cout << a + b;
    system("Pause");
}
Jon Skeet
people
quotationmark

The a + b expression is using your custom operator - so it's as if you'd written (module constness - I'm just trying to get the flavour of what's going on):

B c = a + b;
cout << c;

That doesn't work because the compiler can't find a suitable << operator with a B as the right operand - just as the error message says. It's worth asking yourself what you expected it to do with that.

If you want to print the value of x in the result, perhaps you want:

cout << (a + b).get_x();

people

See more on this question at Stackoverflow