Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider an unknown language with integer and real types in which 1+ 2, 1.0 + 2,

ID: 3589932 • Letter: C

Question

Consider an unknown language with integer and real types in which 1+ 2, 1.0 + 2, 1 + 2.0, and 1.0 + 2.0 are all legal expressions (the question is from the book, Modern Programming Languages: A Practical Introduction by Adam Webber)

a. Explain how this could be the result of coercion, using no overloading.

b. Explain how this could be the result of overloading, using no coercion.

c. Explain how this could result from a combination of overloading and coercion.

d. Explain how this could result from subtype polymorphism, with no overloading or coercion.

Explanation / Answer

Coercion means implicit type conversion. That means even if we are not manually or deliberately converting the type, the compiler is doing that for us implicitly. This is called coersion.

Overloading means having multiple definitions of an operator or function. So in case of overloaded functions, based on the type of arguments, the system decides which definition to use. Similarly in case of overloaded operators, the system decides which definition to use, based on the type of operand.

a. So this can be a result of coercion because compiler may be implicitly converting the data types of the operands to a single common data type and then perform the addition operation.

b. This can be a result of overloading also because we can have different definitions of '+' operator based on the type of operands involved. So if types are int and int, say definition 1 will be invoked. If types are integer and real, say definition 2 will be invoked and so on.

c. Combination of coercion and overloading can also be used to achieve the goal. We can have multiple definitions of '+' operator based on the type of operands involved. So we can have say one definition where both the operands will be implicitly converted to real, and then we can have another definition which will implicitly convert both the operands to integer type.

d. Subtype polymorphism means that in the function definition, we will define a generic type T instead of real or integer. This type T will get its value at runtime.For example

template <class T>

T add(T x, T y)

{

return x + y;

}

So here, at runtime, we can give value to type T as either real or integer.