polymorphism

Hi guys, I need help when overloading << in a base class (the overloading has to be virtual i guess), would anyone give me a brief example?
My teacher didn't explained us that! Thanks in advance!

From my experience it's best not to make virtual operators, but instead you have the operator call a virtual member. This way you only need to overload the operator in the parent class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Parent
{
public:
    friend std::ostream& operator << (std::ostream& strm, const Parent& obj)
    {
        obj.print(strm);
        return strm;
    }

private:
    virtual void print(std::ostream& strm) const;
};

class Child : public Parent
{
private:
    virtual void print(std::ostream& strm) const override
    {
        // ...
    }
};
Thanks, good explanation really, That helped a lot!!!!!

Topic archived. No new replies allowed.