Object-oriented – What’s the difference between a subclass and a subtype

cliskov-substitutionobject-orientedtheory

The highest rated answer to this question about the Liskov Substitution Principle takes pains to distinguish between the terms subtype and subclass. It also makes the point that some languages conflate the two, whereas others do not.

For the object-oriented languages that I am most familiar with (Python, C++), "type" and "class" are synonymous concepts. In terms of C++, what would it mean to have a distinction between subtype and subclass? Say, for example, that Foo is a subclass, but not a subtype, of FooBase. If foo is an instance of Foo, would this line:

FooBase* fbPoint = &foo;

no longer be valid?

Best Answer

Subtyping is a form of type polymorphism in which a subtype is a datatype that is related to another datatype (the supertype) by some notion of substitutability, meaning that program elements, typically subroutines or functions, written to operate on elements of the supertype can also operate on elements of the subtype.

If S is a subtype of T, the subtyping relation is often written S <: T, to mean that any term of type S can be safely used in a context where a term of type T is expected. The precise semantics of subtyping crucially depends on the particulars of what "safely used in a context where" means in a given programming language.

Subclassing should not be confused with subtyping. In general, subtyping establishes an is-a relationship, whereas subclassing only reuses implementation and establishes a syntactic relationship, not necessarily a semantic relationship (inheritance does not ensure behavioral subtyping).

To distinguish these concepts, subtyping is also known as interface inheritance, whereas subclassing is known as implementation inheritance or code inheritance.

References
Subtyping
Inheritance