Getting Polymorphism for friend functions

Hi guys,
I learned that you can manage polymorphism with somthing like this for operator<<.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  
class Base
{ 

public:
friend ostream& operator<<(ostream & out,const Base &b)
{return b.Print(out);}

virtual ostream& Print(ostream &out)
{
out<<"This is Base"<<endl;
return out;
}


};
class Derived:Public Base
{
public:
virtual ostream& Print(ostream & out)
{
out<<"This is Derived"<<endl;
return out;
}
};

But is it possible to do so for some others with a similar catch?
For == or < or something similar?
Last edited on
Your operator<< doesn't need to be a friend.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

class Base
{ 
    int x;
public:
    Base(int x) : x(x) {}
    virtual ~Base() {}
    int getx() const { return x; }
    virtual std::ostream& print(std::ostream& out) const
    {
        return out << "This is Base: " << x;
    }
};

class Derived : public Base
{
    int y;
public:
    Derived(int x, int y) : Base(x), y(y) {}
    std::ostream& print(std::ostream& out) const override
    {
        return out << "This is Derived: " << getx() << ", " << y;
    }
};

std::ostream& operator<<(std::ostream & out, const Base &b)
{
    return b.print(out);
}

int main()
{
    Base *b1 = new Base(1);
    std::cout << *b1 << '\n';
    Base *b2 = new Derived(2, 3);
    std::cout << *b2 << '\n';
    delete b1;
    delete b2;
}

Topic archived. No new replies allowed.