Re: IO-Operator overloading question
From: Jerry Coffin (jcoffin_at_taeus.com)
Date: 07/10/04
- Previous message: SaltPeter: "Re: Heap? what does it mean?"
- In reply to: Francis Glassborow: "Re: IO-Operator overloading question"
- Next in thread: Francis Glassborow: "Re: IO-Operator overloading question"
- Reply: Francis Glassborow: "Re: IO-Operator overloading question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 9 Jul 2004 21:45:53 -0700
Francis Glassborow <francis@robinton.demon.co.uk> wrote in message news:<95zAgTWNVq7AFwnK@robinton.demon.co.uk>...
[ ... ]
> >class B {
> > virtual std::ostream &write(std::ostream &os) {
> > // code to write a B to a stream
> > }
> >
> > friend std::ostream &operator<<(std::ostream &os, B const &b) {
> > return b.write(os);
> > }
> >};
> >
> >class D : public D {
> > virtual std::ostream &write(std::ostream &os) {
> > // code to write a D to a stream.
> > }
> >};
> >
> >The invocation of operator<< itself isn't virtual, but all it does is
> >invoke a virtual member function, which gives the same effect.
>
> And we have no need to involve a friend declaration.
It CAN be written without a friend, by making the virtual I/O function
('write' in the code above) public. With 'write' private as it is
above
With 'write' being private as it is above, the 'friend' is needed --
the code for operator<< is written inside of the class definition, but
it's NOT really a class member -- the 'friend' declaration makes it a
global even though its code is inside of the class definition.
This is necessary, because as a member of B or D, something like
'x<<y' would only resolve to using the function when the LEFT operand
was of type B or D, which it will never be -- it'll always be (some
descendant of) std::ostream.
--
Later,
Jerry.
The universe is a figment of its own imagination.
- Previous message: SaltPeter: "Re: Heap? what does it mean?"
- In reply to: Francis Glassborow: "Re: IO-Operator overloading question"
- Next in thread: Francis Glassborow: "Re: IO-Operator overloading question"
- Reply: Francis Glassborow: "Re: IO-Operator overloading question"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|