Subtypes vs Derived Types in C++

随声附和 提交于 2019-12-08 03:54:53

问题


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


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/13612238/subtypes-vs-derived-types-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!