1
class A {
    //does stuff

public:
    virtual std::ostream& operator<< (std::ostream& os) = 0;
};

class B : public A {
public:
    //does similiar stuff

    virtual std::ostream& operator<< (std::ostream& os) {
        os << "x" << std::endl;
    }
}

class C {
public:
    A* array[10];

    A* & operator()(int a) {
        // in my code, it is a 2D array indexed with (),
        // but that's irrelevant here
        return array[a];
    }
}

int main(){
    C c = C();

    //in for loop we say c(i) = new B();
    for(int i=0; i<10; i++){
        std::cout << *(c(i)); // error
    }

    return 0;
}

I'm guessing the problem is that my () operator returns with base pointer instead of a pointer of B and A doesnt have <<. But using templates for the indexing doesn't solve the problem either, it just makes it weirder.

Any ideas?

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • related/dupe/you should read: https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading – NathanOliver Feb 27 '19 at 15:18

1 Answers1

2

The problem is that you overload the operator<< as a member function. That means it can only be used as e.g.

instance_of_B << std::cout;

which is translated into

instance_of_B.operator<<(std::cout);

If you want to overload << as the stream output operator, it must be a non-member function, and take the stream as the first argument and the A (or derived) object as a second argument.

To handle the output, you could then use a virtual member function that does it, and which is called by the non-member operator<< function.

Perhaps something like

class A
{
public:
    ...

    // Inline definitions of friend functions makes the functions non-member functions
    friend std::ostream& operator<<(std::ostream& os, A const& a)
    {
        return a.output(os);
    }

protected:
    virtual std::ostream& output(std::ostream&) = 0;
};

class B
{
    ...

protected:
    std::ostream& output(std::ostream& os) override
    {
        return os << "Output from the B class\n";
    }
};
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621