I'm writing a C++ program involving polymorphism. I need to overload the operators "<<" and ">>" as friend functions. I have the base class base and 3 derived classes: der1,der2,der3 and a pointer to the base class * p. If I declare the functions as
istream &operator>>(istream &i,der1 &d1) {...}
istream &operator>>(istream &i,der2 &d2) {...}
istream &operator>>(istream &i,der3 &d3) {...}
and call them like
base *p;
p=new der1;
cin>>p;
the program doesn't compile as there's no function with a base parameter. But if I declare it so,it doesn't make any difference if the actual object is of type der1,der2 or der3,although I want it to behave differently depending on the type of the object. All I could think of was to create a virtual function in base and override it the inherited classes. But thus,I'll have to call the functions as
*p>>cin
which doesn't look so natural. How can I solve the problem?
You can create an operator>>
for base class:
istream &operator>>(istream &i, base *b) {
b->ReadFromIstream(i);
return i;
}
Then you make the ReadFromIstream
a virtual function, and overload it from the derived classes. This way you have the same syntax cin >> p
, and they behave differently according to the type of p
.