tags:

views:

120

answers:

3

What are the differences?

+6  A: 

First of all, terminology: it's "Ada", not "ADA" -- it's named after "Ada Lovelace"; it is not an acronym.

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

subtype Week_Days is Integer range 1..7;

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

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 the base type. If, for example, you used:

type Week_Day is new Integer range 1..7;

Then you would not be able to add an integer to a weekday to get another weekday. To do manipulations on a derived type, you'd normally define those manipulations yourself (e.g., create a package). At the same time, a derived type does "inherit" all the operations of its base type (even some that may not make sense) so you do still get addition.

Jerry Coffin
nice explanation!
San Jacinto
I got so sick of explaining the ADA thing, that I now just routinely edit any question or answer that has it wrong and fix it. If someone wants to know why, they can look it up.
T.E.D.
You certainly _could_ add 1 to a Week_Day to get the next Week_Day! But not `Integer'(1)`.
Simon Wright
@Simon:quite right. I've edited the answer to correct that.
Jerry Coffin
+2  A: 

From Wikibooks:

Subtypes of a given 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.

Marc C
+1  A: 

The basic difference is that a derived type is a different type. You cannot just assign one to the other, or use them together in an expression. A subtype on the other hand is assignment-compatible with its original type. You use them together without having to enter any type-munging code.

The subtype will have a narrower range than the base type though, so there may be range checks (from which I believe Constraint_Error can be rasied). So you do still have to be careful.

T.E.D.
A subtype can't have a wider range, but couldn't it have the same range? `subtype My_Float is Float;`
Simon Wright
Yes, it could have the same range. That is one common way to "rename" a type. A smart compiler will probably dispense with constraint checks in that case. It should also dispense with constraint checks inside loops in certian circumstances too. And of course you can disable all constraint checks if you are feeling froggy.
T.E.D.