Effective C++ Ed. 3rd: Item 34. Differenciate between inheritance of interface and inheritance of implementation

 Under public inheritance, use:
  • Pure virtual functions to specify inheritance of interface only.
  • Simple virtual functions to specify inheritance of interface plus inheritance of a default implemetation.
  • Non-virtual functions to specify inheritance of interface plus inheritance of a mandatory implementation.
Note: Instead of using simple virtual functions, we can also use pure virtual function along with their definition as shown:
class Airplane {
public:
  virtual void fly(const Airport& destination) = 0;

  ...

};

void Airplane::fly(const Airport& destination)     // an implementation of
{                                                  // a pure virtual function
  default code for flying an airplane to
  the given destination
}

class ModelA: public Airplane {
public:
  virtual void fly(const Airport& destination)
  { Airplane::fly(destination); }

  ...

};

class ModelB: public Airplane {
public:
  virtual void fly(const Airport& destination)
  { Airplane::fly(destination); }

  ...

};

class ModelC: public Airplane {
public:
  virtual void fly(const Airport& destination);

  ...

};

void ModelC::fly(const Airport& destination)
{
  ... //code for flying a ModelC airplane to the given destination
}

prev | next
Cheers and try hosting at Linode.

No comments:

Post a Comment