As I’ve mentioned in previous posts, I’ve been going through Ivor Horton’s Beginning Visual C++ 2008 and thanks to the good folks at cprogramming.com, I’ve been steered back on course by numerous helpful posts while working through chapter exercises.
For a few weeks now, I’ve been in chapter 9, Inheritance and Polymorphism, and have been extensively taking notes. At one point I veered off course long enough to purchase or checkout from the library several other books, several of which I explored and ended up learning about Inheritance and Polymorphism; so much for a sabbatical!
One of the books I read was C++ Programming in Easy Steps, by Mike McGrath. This served both as a refresher of what I had already covered and a mile-high view of what was to come in with the previously mentioned Inheritance and Polymorphism chapter. All in all it was a great purchase and would serve well as an outline for additional study.
While working through chapter 8, Harnessing Polymorphism, I got hung up on the ability to create a base class pointer and assign it an address of a derived class, as it just didn’t make any sense to me. I just figured it made more sense to have a pointer to a derived class and a pointer to a base class and use them to point to the appropriate objects, but I completely missed the point. As Seraph pointed out on this thread:
You would use a pointer to a base class if you wanted to treat a number of different, but similar objects in the same manner. Chapter 4 of my C++ game tutorial illustrates the use of virtuals in a real world example.
In addition to Seraph’s pseudocode, the following resources were very useful:
- Accelerated C++ – Practical Programming by Example, 1e (pages 232:236)
- C++ Pocket Reference, 1e (pages 91:94) (ebook has latest errata)
- Sams Teach Yourself C++ in 24 Hours, 5e (pages 253:261)
- Thinking in C++, 2e, Volume 1 (pages 632:646)
Out of the those listed, Accelerated C++ and Sams Teach Yourself C++ in 24 Hours gave the best visual representation of what is happening when you assign a derived class address to a pointer to base class.