Docsity

Operator Overloading and Type Conversion in Modern Programming Languages, Exercises of Programming Languages

Toggle sidebar
bg1
Modern Programming Languages
Lecture # 43
Operator Overloading
- Some overloaded operators are common (e.g. โ€˜+โ€™ for int and float)
- Some are potential trouble (e.g. โ€˜*โ€™ in C and C++)
- * is also used for pointers
- Loss of compiler error detection (omission of
an operand should be a detectable error)
- C++ and Ada allow user-defined overloaded operators
Potential problems?
- Users can define nonsense operations
- Readability may suffer
b = a + fun(a);
a=10 fun(a)=5
b=15
int fun(int &x)
{
x = x + 1;
return x*2;
}
a = 10;
b = a + fun(a);
a=11 fun(a)=22
b=33
a=10 fun(a)=22
b=32
32
33
docsity.com
pf3

Partial preview of the text

Download Operator Overloading and Type Conversion in Modern Programming Languages and more Exercises Programming Languages in PDF only on Docsity!

Modern Programming Languages

Lecture # 43

Operator Overloading

  • Some overloaded operators are common (e.g. โ€˜+โ€™ for int and float)
  • Some are potential trouble (e.g. โ€˜*โ€™ in C and C++)
      • is also used for pointers
    • Loss of compiler error detection (omission of an operand should be a detectable error)
  • C++ and Ada allow user-defined overloaded operators

Potential problems?

  • Users can define nonsense operations
  • Readability may suffer

b = a + fun(a);

a=10 fun(a)=

b=

int fun(int &x)

x = x + 1;

return x*2;

a = 10;

b = a + fun(a);

a=11 fun(a)=

b=

a=10 fun(a)=

b=

Type Conversion

  • Implicit Type Conversion
  • Explicit Type Conversion

Implicit Type Conversions

Def: A narrowing conversion is one that converts an object to a type that cannot include all of the values of the original type

Def: A widening conversion is one in which an object is converted to a type that can include at least approximations to all of the values of the original type

Def: A mixed-mode expression is one that has operands of different types

Def: A coercion is an implicit type conversion

Errors in Expressions

- Caused by: - Inherent limitations of arithmetic e.g. division by zero - Limitations of computer arithmetic e.g. overflow

  • Such errors are often ignored by the run-time system Relational Expressions
  • Use relational operators and operands of various types
  • Evaluate to some boolean representation
  • Operator symbols used vary somewhat among different languages (!=, /=, .NE., <>, #)

Boolean Expressions

- Operands are boolean and the result is also a boolean