Question

I recently heard one of my coworkers claim that the concept of a "subtype" is not defined in C++. He claims that "subtypes" are rightly called "derived types" in C++ terminology. Is this true? If I have:

class A { }; class B : public A { };

Can I call B a subtype of A? Or is it only valid to call B a "derived type" of A in C++?

Was it helpful?

Solution

Subtype is not part of the common jargon in C++. The definition in Wikipedia (thanks Chad) is quite broad and in C++ could represent multiple different things, including but not limited to inheritance. For example, all iterator types from a given category and pointers could be subtypes of the iterator concept as they can be substituted in templates that require that concept (including the standard library algorithms).

I would use derived in general, other alternative words for the same (in different languages) could include extends (type A extends B) or inherits.

OTHER TIPS

A subtype is a specialized version of a type. In C++ a derived class is a subtype (subclass) of a base class type. A variable of the derived type could appear anywhere that a variable of the parent type is requested. A subtype of another type means you can use the subtype in all situations where the parent type could be used.

From MSDN:

Derived types are new types that can be used in a program, and can include directly derived types and composed derivative types.

According to wikipedia:

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.

This definition means that public inheritance fits for the following classes:

class T {};
class S : public T {};

However, C++ also provides private and protected inheritance, and these do not model the "is-a" relationship that public inheritance does, and therefore these types of inheritance do not meet the definition of subtype (as provided by wikipedia).

Subtype is not a common way in C++ to describe these relationships, even in the cases where the definition does appear to fit (public inheritance).

Stroustrup seems to prefer "derived class" but will also call it a "subclass": see this link.

In http://www.stroustrup.com/hopl2.pdf he writes,

The derived class concept is C++’s version of Simula’s prefixed class notion and thus a sibling of Smalltalk’s subclass concept. The names derived class and base class were chosen because I never could remember what was sub and what was super and observed that I was not the only one with this particular problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top