6 Smart pointers and polymorphism

 

This chapter covers

  • Using inheritance for dynamic polymorphism
  • Special member functions
  • Type traits
  • Using smart pointers
  • Random number distributions

In this chapter, we will work with classes again, but this time using inheritance. We will create various "Blob" classes. Our blobs will be able to move forward and backward. If we get our blobs in a line at the bottom of a virtual paper bag, we can set them off racing and see which blob escapes the paper bag first. Separately from practicing with classes, we can then claim and furthermore prove that we can code our way out of a paper bag, a skill all programmers should aim for.

We will start with a simple class hierarchy and create a blob that takes a step at a time. We will consider which special member functions we need when we use inheritance and use type traits to interrogate various member functions. We will use random numbers again, using various distributions to decide how big a step a blob takes. The randomness will make the race more exciting. By storing a blob in a smart pointer, we can keep various types of blobs in a vector. Their behavior will vary depending on the type of blob, giving us dynamic polymorphism. They can then race, and we can sit back, watch, and congratulate ourselves on coding our way out of a paper bag.

6.1 A class hierarchy

6.1.1 An abstract base class

6.1.2 A concrete class

6.1.3 Warming up for a race

6.1.4 Using type traits to check for special member functions

6.2 Writing and using derived classes in a vector

6.2.1 A blob moving randomly

6.2.2 Smart pointers

6.2.3 Race!

6.2.4 Some design considerations

Summary

sitemap