Re: I need help understanding inheritance and virtual functions
On May 8, 10:29 am, Juha Nieminen <nos...@thanks.invalid> wrote:
dwightarmyofchampi...@hotmail.com wrote:
why not just originally define the object to be of type
Derived* in the first place?
I think the C++ streams are a perfect example of
object-oriented programming (including dynamic binding, ie.
virtual functions) in action.
Actually, they are a masterful example of using the most
appropriate technique to support customization, depending on the
type of customization desired. They use polymorphism for one
type of customization, and function overloading for the other.
For example, suppose you have a function like this:
void printSomethingTo(std::ostream& os)
{
os << "Something";
}
std::ostream is a *base class* from which several other types
of stream classes have been derived. The printSomethingTo()
function above takes a reference of this base class type, but
doesn't really know what it's really given. However, it
doesn't have to: It can still output the string to whatever it
was given, as long as it has been derived from that base
class.
Yes, but that's not really a good example, because the functions
involved aren't virtual, and may not even be members. The
important point is that when the ostream, here, decides to
output a character, it calls a virtual function in the
associated streambuf. Which then does whatever is appropriate.
(It's actually a bit more complicated than that, because the
base class, streambuf, is more than just an interface; it uses
the template method pattern to customize its action, only
calling the virtual function when it has no room in its buffer.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34