Subtypes vs Derived Types in C++

2019-06-01 03:07发布

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++?

4条回答
一夜七次
2楼-- · 2019-06-01 03:55

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).

查看更多
疯言疯语
3楼-- · 2019-06-01 03:57

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.

查看更多
小情绪 Triste *
4楼-- · 2019-06-01 03:57

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.

查看更多
再贱就再见
5楼-- · 2019-06-01 04:00

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.

查看更多
登录 后发表回答