Archive

Posts Tagged ‘Derivation’

C++ Class Hierarchies Crash Course: Derivation (“is-a”) vs Composition (“has-a”), and Is a Square a Rectangle?

March 5, 2013 4 comments

In this article I’m going to rattle over some basic design choice dilemmas you might face when trying to organize classes into a hierarchy. We’ll look at standard derivation (the “is-a” relationship), composition (the “has-a” relationship), when to use which, and also touch briefly on interfaces and private inheritance.

Pre-requisites you should know before reading:

  • how to define a class in C++
  • what a constructor is and how to define one
  • the difference between public and private members

The “Is-a” Relationship

Is a square a type of rectangle? Is a rectangle a type of square? Or is a square merely a rectangle with a certain set of properties (identical width and height)? Are circles and rectangles both types of shape, or are they even related at all? The answers to these questions have nothing to do with your natural intuition or experience from the real world (although that helps sometimes), but rather, what you are planning to do with them in your code.

Read more…

Categories: C++ Tags: , , , ,
%d bloggers like this: