CS253: Software Development with C++

Fall 2022

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 {
  // stuff goes here
};

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

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