how to make operator << a virtual function?

V

Victor

Anyone knows how to write a virtual function for operator<< ?
I have a base class and some public derived class from it.
For the derived class, I hope they can use << to output their
different data. What's more, I want the base class pointers
can access the derived ones and then their corresponding
operator <<. For example:

class base {
// virtual and friend can't be put together, so the following
// code won't work.
virtual friend ostream& operator<< (ostream& os, const base& b);
};
class derived1 : public base
{
virtual friend ostream& operator<< (ostream& os, const base& d1);
};
class derived2 : public base
{
virtual friend ostream& operator<< (ostream& os, const base& d2);
};

I hope they can work like:
base *pb;
derived1 d1;
derived2 d2;
cout<<d1<<"\t"<<d2<<endl; // use their corresponding defination
pb = &d1; // point to class derived1
cout<<*pb<<endl; // use the operator<< defined in class derived1
pb = &d2; // point to class derived2
cout<<*pb<<endl; // use the operator<< defined in class derived2

How could I implement the operator overloading then? thanks.
 
D

David Harmon

On Sat, 10 Apr 2004 21:38:19 -0400 in comp.lang.c++, "Victor"
Anyone knows how to write a virtual function for operator<< ?

Public:
virtual ostream & print_on(ostream &) const;
} // end class


inline ostream& operator<< (ostream& os, const base& me)
{
return me.print_on(os);
}
 
L

Leor Zolman

Anyone knows how to write a virtual function for operator<< ?

The canonical way to accomplish this is to have a virtual member function
in each class of your heirarchy, say

class base {
public:
virtual ostream &put(ostream &);
// ...
};

class derived : public base {
public:
ostream &put(ostream &);
// ...
};
// etc.

Each implementation of put() simply "puts" *this to the stream, and returns
the stream reference it was passed. Then you'd write a single non-member
(of course) operator<< as follows:

ostream &operator<<(ostream &os, const base &b)
{
return b.put(os);
}

This will dispatch to the appropriate virtual put() function when called
with any ref to the base or derived class(es) as the 2nd operand.
-leor
 
V

Victor

Good idea. It works. Thanks very much

David Harmon said:
On Sat, 10 Apr 2004 21:38:19 -0400 in comp.lang.c++, "Victor"


Public:
virtual ostream & print_on(ostream &) const;
} // end class


inline ostream& operator<< (ostream& os, const base& me)
{
return me.print_on(os);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,589
Members
45,100
Latest member
MelodeeFaj
Top