Derived types and subtypes in Ada

What are the differences?

+4
source share
3 answers

First of all, terminology: this is โ€œAdaโ€, not โ€œADAโ€ - it is named after โ€œAda Lovelaceโ€; it is not an abbreviation.

The subtype is compatible with its base type, so you can mix the operands of the base type with the operands of the base type. For instance:

subtype Week_Days is Integer range 1..7; 

Since this is a subtype, you can (for example) add 1 on a weekday to get the next business day.

A derived type is a completely separate type that has the same characteristics as its base type. You cannot mix operands of a derived type with operands of a base type. If, for example, you used:

 type Week_Day is new Integer range 1..7; 

Then you cannot add an integer on a weekday to get another weekday. To manipulate a derived type, you usually define these manipulations yourself (for example, create a package). At the same time, the derived type "inherits" all the operations of its base type (even some of them may not make sense), so you still get the addition.

+6
source

From Wikibooks :

Subtypes of this type will be compatible with each other.

A derived type is a new, full-blown type created from an existing one. Like any other type, it is incompatible with its parent; however, it inherits the primitive operations defined for the parent type.

+2
source

The main difference is that the derived type is of a different type . You cannot just assign to each other or use them together in an expression. A subtype, on the other hand, is compatible with the original type. You use them together without entering any type of code.

The subtype will have a narrower range than the base type, so there may be range checks (of which I believe that Constraint_Error can be compressed). Therefore, you should still be careful.

+1
source

Source: https://habr.com/ru/post/1307476/


All Articles