Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making operator<< virtual?

I need to use a virtual << operator. However, when I try to write:

virtual friend ostream & operator<<(ostream& os,const Advertising& add); 

I get the compiler error

Error 1 error C2575: 'operator <<' : only member functions and bases can be virtual

How can I turn this operator virtual?

like image 310
inna karpasas Avatar asked Dec 31 '10 18:12

inna karpasas


People also ask

Can operator == be virtual?

Virtual functions don't know about parameter's inheritance: So even though in the following example, operator= is made virtual, the call will never act as a virtual function in D, because the parameters and return value of operator= are different.

Can overloaded operators be virtual?

If you want to override a virtual function in a child-class, then you need to declare the function override in the child class. So yes, the declaration is needed.

What is << operator in cout?

In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input. We must know the following things before we start overloading these operators. 1) cout is an object of ostream class and cin is an object of istream class. 2) These operators must be overloaded as a global function ...

Could we define operator << as a member function?

You can not do it as a member function, because the implicit this parameter is the left hand side of the << -operator. (Hence, you would need to add it as a member function to the ostream -class.


1 Answers

The problem with this setup is that the operator<< you defined above is a free function, which can't be virtual (it has no receiver object). In order to make the function virtual, it must be defined as a member of some class, which is problematic here because if you define operator<< as a member of a class then the operands will be in the wrong order:

class MyClass { public:     virtual ostream& operator<< (ostream& out) const; }; 

means that

MyClass myObject; cout << myObject; 

will not compile, but

MyClass myObject; myObject << cout; 

will be legal.

To fix this, you can apply the Fundamental Theorem of Software Engineering - any problem can be solved by adding another layer of indirection. Rather than making operator<< virtual, consider adding a new virtual function to the class that looks like this:

class MyClass { public:     virtual void print(ostream& where) const; }; 

Then, define operator<< as

ostream& operator<< (ostream& out, const MyClass& mc) {     mc.print(out);     return out; } 

This way, the operator<< free function has the right parameter order, but the behavior of operator<< can be customized in subclasses.

Hope this helps!

like image 136
templatetypedef Avatar answered Oct 08 '22 01:10

templatetypedef