0
    class Shape
    {
        virtual void out() = 0;
    };

    std::ostream& operator<<(std::ostream& os, Shape& a)
    {
        return os << a.out();
    }

I want to create an abstract base class and be able to simply use cout << Triangle/Square etc. later on, with Triangle, Square being derived classes from Shape.

It works fine if I simply say return os << "test"; so I'm guessing it's something to do with a.out() not getting called properly, I just can't seem to pinpoint the problem.

2
  • How are you calling the operator? Commented May 4, 2013 at 16:13
  • You should be taking a by const reference. Commented May 4, 2013 at 16:39

1 Answer 1

5

The out member function returns void, so it doesn't return an object for you to pass to std::ostream::operator<<. Perhaps you want it to return std::string?

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

3 Comments

wow right, I wanted to simply call the function from this operator then I realized (if I'm correct) I have to pass it something, and completely forgot about the original function being void. Can I not pass the os anything in the operator<< or should I just pass a string from the out function?
@SaintHUN Either pass the stream as an argument to the function and keep it void, or let the function return a string. I recommend the first alternative.
Works perfectly thanks, and sorry for such an easy question. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.