In article <3F6C8FBB.41DF4503@rogers.com>,
virzak@rogers.com says...[color=blue]
> Hello,
>
> I have an ABC.
> it supports:
> ostream & operator <<
>
> I also have a derived class that supports this operator.
>
> How can I call operator << of the base class for derived object??? Is it
> at all possible?[/color]
IMO, it's better to avoid this as a rule. Instead, I'd use vaguely
along these lines:
#include <iostream>
class base {
int base_member;
protected:
virtual std::ostream &write(std::ostream &os) const {
return os << base_member << "\n";
}
// This only looks like a member function. It's really global.
friend std::ostream &operator<<(std::ostream &os, base const &b) {
return b.write(os);
}
public:
base(int init = 0) : base_member(init) { }
};
class derived : public base {
int derived_member;
virtual std::ostream &write(std::ostream &os) const {
base::write(os);
return os << derived_member << "\n";
}
public:
derived(int b_init, int d_init) : base(b_init), derived_member
(d_init) { }
};
#ifdef TEST
int main() {
base &b = *(new derived(0, 1));
std::cout << b;
return 0;
}
#endif
The friend operator<< can't be virtual itself, but because it calls a
virtual function, it invokes either base::write or derived::write,
depending on the type that's actually passed to it. If it was a derived
object, that explicitly calls the base::write to handle whatever the
base needs to do, then it writes out its own members.
At last IMO, the client code is NOT the place to deal with things like
this -- one of the fundamental points of object orientation is that the
object should hide details of its implementation, so this should really
be handled by the object itself (as above) rather than in client code
(as you were trying to do it). Of course, there are a few exceptions to
this kind of rule -- just for an obvious one, it might be reasonable to
print out some things during debugging that you won't under normal
circumstances, and it's often perfectly reasonable for the debugging
and/or testing code to know more about the object than the world at
large is supposed to.
--
Later,
Jerry.
The universe is a figment of its own imagination.