brfh
brfh

Reputation: 344

How can i overload operator as virtual

I have a simple inheritance structure:

I want to overload << and >> operators to input and print data in objects Derived1 and Derived2 classes as a reference to Base class.

Can I declare some kind of virtual functions? Like this :

virtual std::ostream& operator<<(std::ostream& os, const Base& obj) = 0;
virtual std::istream& operator>>(std::istream& is, Base& obj) = 0;

in my Base class, and override them in Derived1 and Derived2 classes?

I want to do some things like that:

std::vector<Base&> a;
... push reference to Derived1 and Derived2 objects ...
for (auto i = a.begin(); i != a.end(); ++i) std::cin >> (*i);
for (auto i = a.begin(); i != a.end(); ++i) std::cout << (*i);

Upvotes: 2

Views: 705

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136306

Only member functions can be virtual, but these operator<< and operator>> cannot be member functions of your class because their first argument is a stream, not the class that overloads these operators.

You can overload operator<< and operator>> adaptor functions for your class, which forward the call into the corresponding virtual functions of your class (the 2nd argument):

#include <iostream>

struct Base {
    virtual std::ostream& output(std::ostream&) const = 0;
    virtual std::istream& input(std::istream&) = 0;
    virtual ~Base() = default;
};

inline std::ostream& operator<<(std::ostream& os, const Base& obj) { return obj.output(os); }
inline std::istream& operator>>(std::istream& is, Base& obj) { return obj.input(is); }

Upvotes: 5

Related Questions