Posts tagged ‘inheritance’

C++ is bad: inheritance is counterintuitive

In our latest installment of “why not to program in C++,” let’s take a look at a simple class hierarchy:

class Duck {
 public:
  Duck() {
    InitializeMigratoryRoute();
  }

  // Default behavior is nonmigratory; this is
  // overridden in the Mallard class.
  virtual void InitializeMigratoryRoute();
}

class Mallard : public Duck {
 public:
  Mallard();

  // Migrate south in the fall and north in the spring
  virtual void InitializeMigratoryRoute();
}

class DonaldDuck : public Duck {
 public:
  DonaldDuck() {
    outfit_.AddShirt(Outfit::Shirts::SAILOR);
    outfit_.AddHat(Outfit::Hats::SAILOR);
  }

 private:
  Outfit outfit_;
}

You can assume this code compiles and runs (i.e., the Outfit class is defined, it implements AddShirt(), both versions of InitializeMigratoryRoute() are defined, etc). I would say this looks like perfectly reasonable code: its intention is clear and straightforward, and any sane language should have no trouble implementing this. [1] However, we’re dealing with C++, which means there are always more problems, and in fact this code is not in the least alright. In particular, there are two major things wrong with it. Do you see what they are?

This code has two major problems. →