Posted by Matt Green on April 07, 2001 at 15:54:53:
In Reply to: Re: Ptr to abstract base type posted by Daniel Longest on April 07, 2001 at 03:28:17:
: Suppose our abstact base class is called ABC. Suppose we then derive from it two classes, Der1 and Der2. ABC being an ABC implies there is at least one pure virtual function that Der1 and Der2 must each implement, let's say it's print. If we want to use a bunch of Der1's and Der2's, you could have a list of each separately and that's fine. But that eliminates using inheritance. You can store one list of ABC pointers, and everytime you create a derived object, you can upcast it without trouble. Then if you call the approrpriate print function from any item in the list, the approrpriate print will be called. I probably explained that awkwardly so i'll try to rephrase. (The following assumes usage of pointers). C++ wants to typecast as soon as possible. If possible, it will do so statically, at compile time. That means that without a virtual function, the function call wil be based on the type of pointer you have. This means that the wrong function will be called if you have a base class pointer pointing to a derived object. But with virtual functions, this call wil be postponed til runtime when it will check the type of the object pointed to. Then, the call will work correctly, the function for the derived object will be called, because it is the pointed-to type. I hope I explained that well enough, it's hard to do without a good example. I suggest another book, "C++ FAQs" by Cline, Lomow, Girou, excellent in its coverage of how to use the OO features of C++. (Cline wrote the comp.lang.c++ online FAQ, http://www.parashift.com/cpp-faq-lite/ ) Note that many base classes have virtual destructors, this makes them suitable for inheritance because the proper destructor will be called based on the type at runtime. This is why most of the STL should not be inherited from, the classes do not have virtual destructors.
: : From the spec: "The creature list must store a pointer of the (abstract) base type from the creature inheritance hierarchy. This must not be of any actual creature type."
: : What does this mean? I don't see the point in it, but thats probably since I don't totally understand it.
: : Matt
Is this just making some sort of list-type data structure to hold pointers to the base type, where each entry is a derived type?
Post a Followup