CS253: Software Development with C++

Fall 2021

Inheritance Vs Composition

Show Lecture.InheritanceVsComposition as a slide show.

CS253 Inheritance Vs Composition

Is-a vs. Has-a

It’s all about

Inheritance (Is-a)

vs.

Composition (Has-a)

Is-a

Has-a

O-O relevance

In object-oriented (o-o) programming:

Example

class Base {
  public:
    int beta;
};

class Derived : public Base {
  public:
    int gamma;
};

Is-a is transitive

class Mammal { };

class Feline : public Mammal { };

class Housecat : public Feline { };

Another Example

class RapSheet {
  ...
};

class Inmate {
  private:
    string name;
    unsigned long number;
    RapSheet offenses;
};

Of course, is-a is restricted to class objects, whereas has-a can apply to objects or built-in types.