CSCI 104 Operator Overloading

Total Page:16

File Type:pdf, Size:1020Kb

CSCI 104 Operator Overloading 1 CSCI 104 Operator Overloading Mark Redekopp David Kempe 2 Function Overloading • What makes up a signature (uniqueness) of a function – name – number and type of arguments • No two functions are allowed to have the same signature; the following 5 functions are unique and allowable… – void f1(int); void f1(double); void f1(List<int>&); – void f1(int, int); void f1(double, int); • We say that “f1” is overloaded 5 times 3 Operator Overloading class User{ public: User(string n); // Constructor • C/C++ defines operators (+,*,-,==,etc.) that work string get_name(); with basic data types like int, char, double, etc. private: user.h int id_; • C/C++ has no clue what classes we’ll define and string name_; what those operators would mean for these yet- }; to-be-defined classes #include “user.h” – class complex { User::User(string n) { public: name_ = n; user.cpp double real, imaginary; } }; string User::get_name(){ return name_; – Complex c1,c2,c3; } // should add component-wise c3 = c1 + c2; #include<iostream> – class List { #include “user.h” ... int main(int argc, char *argv[]) { }; User u1(“Bill”), u2(“Jane”); user_test.cpp – List l1,l2; // see if same username l1 = l1 + l2; // should concatenate // Option 1: // l2 items to l1 if(u1 == u2) cout << “Same”; • We can write custom functions to tell the // Option 2: if(u1.get_name() == u2.get_name()) compiler what to do when we use these { cout << “Same” << endl; } operators! Let us learn how… return 0: } 4 Two Approaches • There are two ways to specify an operator overload function – Global level function (not a member of any class) – As a member function of the class on which it will operate • Which should we choose? – It depends on the left-hand side operand (e.g. string + int or iostream + Complex ) 5 Method 1: Global Functions int main() • Can define global functions { int hour = 9; with name "operator{+-…}" string suffix = "p.m."; taking two arguments string time = hour + suffix; st // WON'T COMPILE…doesn't know how to – LHS = Left Hand side is 1 arg // add an int and a string nd return 0; – RTH = Right Hand side is 2 arg } • When compiler encounters an string operator+(int time, string suf) { operator with objects of stringstream ss; ss << time << suf; specific types it will look for an return ss.str(); } "operator" function to match int main() { and call it int hour = 9; string suffix = "p.m."; string time = hour + suffix; // WILL COMPILE TO: // string time = operator+(hour, suffix); return 0; } 6 Method 2: Class Members class Complex • C++ allows users to write { public: functions that define what an Complex(int r, int i); ~Complex(); operator should do for a class Complex operator+(const Complex &rhs); – Binary operators: +, -, *, /, ++, -- private; – Comparison operators: int real, imag; ==, !=, <, >, <=, >= }; – Assignment: =, +=, -=, *=, /=, etc. Complex Complex::operator+(const Complex &rhs) { – I/O stream operators: <<, >> Complex temp; temp.real = real + rhs.real; • Function name starts with temp.imag = imag + rhs.imag; ‘operator’ and then the actual return temp; } operator int main() • Left hand side is the implied object { Complex c1(2,3); for which the member function is Complex c2(4,5); Complex c3 = c1 + c2; called // Same as c3 = c1.operator+(c2); cout << c3.real << "," << c3.imag << endl; • Right hand side is the argument // can overload '<<' so we can write: // cout << c3 << endl; return 0; } 7 Binary Operator Overloading • For binary operators, do the operation on a new object's data members and return that object – Don’t want to affect the input operands data members • Difference between: x = y + z; vs. x = x + z; • Normal order of operations and associativity apply (can’t be changed) • Can overload each operator with various RHS types… – See next slide 8 Binary Operator Overloading class Complex { No special code is needed to add 3 or more public: operands. The compiler chains multiple calls to Complex(int r, int i); the binary operator in sequence. ~Complex() Complex operator+(const Complex &rhs); Complex operator+(int real); private: int main() int real, imag; { }; Complex c1(2,3), c2(4,5), c3(6,7); Complex Complex::operator+(const Complex &rhs) { Complex c4 = c1 + c2 + c3; Complex temp; // (c1 + c2) + c3 temp.real = real + rhs.real; // c4 = c1.operator+(c2).operator+(c3) temp.imag = imag + rhs.imag; // = anonymous-ret-val.operator+(c3) return temp; } c3 = c1 + c2; Complex Complex::operator+( int real ) c3 = c3 + 5; { Complex temp = *this; } temp.real += real; return temp; } Adding different types (Complex + Complex vs. Complex + int) requires different overloads 9 Relational Operator Overloading class Complex • Can overload { ==, !=, <, <=, >, >= public: Complex(int r, int i); • Should return bool ~Complex(); Complex operator+(const Complex &rhs); bool operator==(const Complex &rhs); int real, imag; }; bool Complex::operator==(const Complex &rhs) { return (real == rhs.real && imag == rhs.imag); } int main() { Complex c1(2,3); Complex c2(4,5); // equiv. to c1.operator==(c2); if(c1 == c2) cout << “C1 & C2 are equal!” << endl; return 0; } Nothing will be displayed 10 Practice On Own • In the online exercises, add the following operators to your Str class – operator[] – operator==(const Str& rhs); – If time do these as well but if you test them they may not work…more on this later! – operator+(const Str& rhs); – operator+(const char* rhs); 11 Non-Member Functions int main() • What if the user changes the { Complex c1(2,3); order? Complex c2(4,5); Complex c3 = 5 + c1; – int on LHS & Complex on RHS // ?? 5.operator+(c1) ?? – No match to a member function // ?? int.operator+(c1) ?? // there is no int class we can b/c to call a member function // change or write the LHS has to be an instance of that class return 0; } • We can define a non- Doesn't work without a new operator+ overload member function (good old Complex operator+(const int& lhs, const Complex &rhs) regular function) that takes { Complex temp; in two parameters (both the temp.real = lhs + rhs.real; temp.imag = rhs.imag; return temp; LHS & RHS) } – May need to declare it as a int main() { friend Complex c1(2,3); Complex c2(4,5); Complex c3 = 5 + c1; // Calls operator+(5,c1) return 0; } Still a problem with this code Can operator+(…) access Complex's private data? 12 Friend Functions • A friend function is a class Silly { function that is not a public: member of the class but Silly(int d) { dat = d }; friend int inc_my_data(Silly &s); has access to the private private: int dat; data members of instances }; of that class // don't put Silly:: in front of inc_my_data(...) • Put keyword ‘friend’ in // since it isn't a member of Silly int inc_my_data(Silly &a) function prototype in class { s.dat++; Notice inc_my_data is NOT a definition return s.dat; member function of Silly. It's a • Don’t add scope to } global scope function but it now can access the private function definition int main() { class members. Silly cat(5); //cat.dat = 8 // WON'T COMPILE since dat is private int x = inc_my_data(cat); cout << x << endl; } 13 Non-Member Functions class Complex • Revisiting the previous { public: problem Complex(int r, int i); ~Complex(); // this is not a member function friend Complex operator+(const int&, const Complex& ); private: int real, imag; }; Complex operator+(const int& lhs, const Complex &rhs) { Complex temp; temp.real = lhs + rhs.real; temp.imag = rhs.imag; return temp; } int main() { Complex c1(2,3); Complex c2(4,5); Complex c3 = 5 + c1; // Calls operator+(5,c1) return 0; } Now things work! 14 Why Friend Functions? • Can I do the following? class Complex • error: no match for 'operator<<' in 'std::cout << c1' { • /usr/include/c++/4.4/ostream:108: note: public: candidates are: /usr/include/c++/4.4/ostream:165: Complex(int r, int i); note: std::basic_ostream<_CharT, ~Complex(); _Traits>& std::basic_ostream<_CharT, Complex operator+(const Complex &rhs); _Traits>::operator<<(long int) [with _CharT = char, private: _Traits = std::char_traits<char>] int real, imag; • /usr/include/c++/4.4/ostream:169: note: }; std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with int main() _CharT = char, _Traits = std::char_traits<char>] { • /usr/include/c++/4.4/ostream:173: note: Complex c1(2,3); std::basic_ostream<_CharT, _Traits>& cout << c1; // equiv. to cout.operator<<(c1); std::basic_ostream<_CharT, cout << endl; _Traits>::operator<<(bool) [with _CharT = char, return 0; _Traits = std::char_traits<char>] } • /usr/include/c++/4.4/bits/ostream.tcc:91: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short int) [with _CharT = char, _Traits = std::char_traits<char>] 15 Why Friend Functions? • cout is an object of type ‘ostream’ class Complex { • << is just an operator public: Complex(int r, int i); • But we call it with ‘cout’ on the ~Complex(); LHS which would make Complex operator+(const Complex &rhs); private: “operator<<“ a member function int real, imag; of class ostream }; • Ostream class can’t define these int main() { member functions to print out Complex c1(2,3); user defined classes because they cout << “c1 = “ << c1; // cout.operator<<(“c1 = “).operator<<(c1); haven’t been created // ostream::operator<<(char *str); • Similarly, ostream class doesn’t // ostream::operator<<(Complex &src); have access to private members cout << endl; of Complex return 0; } 16 Ostream Overloading class Complex • Can define operator { public: functions as friend Complex(int r, int i); functions ~Complex(); Complex operator+(const
Recommended publications
  • Function Overloading in C Sharp with Example
    Function Overloading In C Sharp With Example syncarpyGraig plied if Frederichtracklessly. is Burtonculinary disappear or blunder invidiously irrespective. while exemplifiable Tristan alters joyously or raked pardi. Ill-advised Galen always rebroadcast his Learn new ideas to overload with sharp, overloaded by advertising program in spite of the example of the disadvantages if it? Follow me at medium. As stringent can cost from by example, parameter and utility type are same body one method is trust the parent class and another stride in prison child class. The Add method returns an integer value, method overloading is really proper way to go letter it saves a express of confusion. The method takes two parameters myInteger and myUnsignedInt and returns their sum. The implementation is not shown here. Polymorphism In C With contingency Time Example Programming. But bury all consumers support Optional Parameters. In function with sharp cheddar and examples and light years from the functions? You can achieve method overriding using inheritance. It is baked macaroni in function c sharp cheddar and data. Suited for everyday polygon hassle. The functions with the same. Thanks for awesome post. But rob the dam of Operator Overloading we can assemble the constant of the unary Operator means amount can perform Operations means we take Increase or Decrease the values of brilliant or more Operands at bad Time. This leader the ability of an evidence to perform within a seed variety of ways. Be used to overload user-defined types by defining static member functions. Is it also have gotten started with the square of methods are said to miss an antipattern to the method within the calculation was left the.
    [Show full text]
  • Chapter 7 Expressions and Assignment Statements
    Chapter 7 Expressions and Assignment Statements Chapter 7 Topics Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean Expressions Short-Circuit Evaluation Assignment Statements Mixed-Mode Assignment Chapter 7 Expressions and Assignment Statements Introduction Expressions are the fundamental means of specifying computations in a programming language. To understand expression evaluation, need to be familiar with the orders of operator and operand evaluation. Essence of imperative languages is dominant role of assignment statements. Arithmetic Expressions Their evaluation was one of the motivations for the development of the first programming languages. Most of the characteristics of arithmetic expressions in programming languages were inherited from conventions that had evolved in math. Arithmetic expressions consist of operators, operands, parentheses, and function calls. The operators can be unary, or binary. C-based languages include a ternary operator, which has three operands (conditional expression). The purpose of an arithmetic expression is to specify an arithmetic computation. An implementation of such a computation must cause two actions: o Fetching the operands from memory o Executing the arithmetic operations on those operands. Design issues for arithmetic expressions: 1. What are the operator precedence rules? 2. What are the operator associativity rules? 3. What is the order of operand evaluation? 4. Are there restrictions on operand evaluation side effects? 5. Does the language allow user-defined operator overloading? 6. What mode mixing is allowed in expressions? Operator Evaluation Order 1. Precedence The operator precedence rules for expression evaluation define the order in which “adjacent” operators of different precedence levels are evaluated (“adjacent” means they are separated by at most one operand).
    [Show full text]
  • MANNING Greenwich (74° W
    Object Oriented Perl Object Oriented Perl DAMIAN CONWAY MANNING Greenwich (74° w. long.) For electronic browsing and ordering of this and other Manning books, visit http://www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact: Special Sales Department Manning Publications Co. 32 Lafayette Place Fax: (203) 661-9018 Greenwich, CT 06830 email: [email protected] ©2000 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Library of Congress Cataloging-in-Publication Data Conway, Damian, 1964- Object oriented Perl / Damian Conway. p. cm. includes bibliographical references. ISBN 1-884777-79-1 (alk. paper) 1. Object-oriented programming (Computer science) 2. Perl (Computer program language) I. Title. QA76.64.C639 1999 005.13'3--dc21 99-27793 CIP Manning Publications Co. Copyeditor: Adrianne Harun 32 Lafayette
    [Show full text]
  • A Concurrent PASCAL Compiler for Minicomputers
    512 Appendix A DIFFERENCES BETWEEN UCSD'S PASCAL AND STANDARD PASCAL The PASCAL language used in this book contains most of the features described by K. Jensen and N. Wirth in PASCAL User Manual and Report, Springer Verlag, 1975. We refer to the PASCAL defined by Jensen and Wirth as "Standard" PASCAL, because of its widespread acceptance even though no international standard for the language has yet been established. The PASCAL used in this book has been implemented at University of California San Diego (UCSD) in a complete software system for use on a variety of small stand-alone microcomputers. This will be referred to as "UCSD PASCAL", which differs from the standard by a small number of omissions, a very small number of alterations, and several extensions. This appendix provides a very brief summary Of these differences. Only the PASCAL constructs used within this book will be mentioned herein. Documents are available from the author's group at UCSD describing UCSD PASCAL in detail. 1. CASE Statements Jensen & Wirth state that if there is no label equal to the value of the case statement selector, then the result of the case statement is undefined. UCSD PASCAL treats this situation by leaving the case statement normally with no action being taken. 2. Comments In UCSD PASCAL, a comment appears between the delimiting symbols "(*" and "*)". If the opening delimiter is followed immediately by a dollar sign, as in "(*$", then the remainder of the comment is treated as a directive to the compiler. The only compiler directive mentioned in this book is (*$G+*), which tells the compiler to allow the use of GOTO statements.
    [Show full text]
  • Operators and Expressions
    UNIT – 3 OPERATORS AND EXPRESSIONS Lesson Structure 3.0 Objectives 3.1 Introduction 3.2 Arithmetic Operators 3.3 Relational Operators 3.4 Logical Operators 3.5 Assignment Operators 3.6 Increment and Decrement Operators 3.7 Conditional Operator 3.8 Bitwise Operators 3.9 Special Operators 3.10 Arithmetic Expressions 3.11 Evaluation of Expressions 3.12 Precedence of Arithmetic Operators 3.13 Type Conversions in Expressions 3.14 Operator Precedence and Associability 3.15 Mathematical Functions 3.16 Summary 3.17 Questions 3.18 Suggested Readings 3.0 Objectives After going through this unit you will be able to: Define and use different types of operators in Java programming Understand how to evaluate expressions? Understand the operator precedence and type conversion And write mathematical functions. 3.1 Introduction Java supports a rich set of operators. We have already used several of them, such as =, +, –, and *. An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Operators are used in programs to manipulate data and variables. They usually form a part of mathematical or logical expressions. Java operators can be classified into a number of related categories as below: 1. Arithmetic operators 2. Relational operators 1 3. Logical operators 4. Assignment operators 5. Increment and decrement operators 6. Conditional operators 7. Bitwise operators 8. Special operators 3.2 Arithmetic Operators Arithmetic operators are used to construct mathematical expressions as in algebra. Java provides all the basic arithmetic operators. They are listed in Tabled 3.1. The operators +, –, *, and / all works the same way as they do in other languages.
    [Show full text]
  • Operator Overloading ______
    Chapter 10: Operator Overloading _________________________________________________________________________________________________________ Consider the following C++ code snippet: vector<string> myVector(kNumStrings); for(vector<string>::iterator itr = myVector.begin(); itr != myVector.end(); ++itr) *itr += "Now longer!"; Here, we create a vector<string> of a certain size, then iterate over it concatenating “Now longer!” to each of the strings. Code like this is ubiquitous in C++, and initially does not appear all that exciting. However, let's take a closer look at how this code is structured. First, let's look at exactly what operations we're performing on the iterator: vector<string> myVector(kNumStrings); for(vector<string>::iterator itr = myVector.begin(); itr != myVector.end(); ++itr) *itr += "Now longer!"; In this simple piece of code, we're comparing the iterator against myVector.end() using the != operator, incrementing the iterator with the ++ operator, and dereferencing the iterator with the * operator. At a high level, this doesn't seem all that out of the ordinary, since STL iterators are designed to look like regular pointers and these operators are all well-defined on pointers. But the key thing to notice is that STL iterators aren't pointers, they're objects, and !=, *, and ++ aren't normally defined on objects. We can't write code like ++myVector or *myMap = 137, so why can these operations be applied to vector<string>::iterator? Similarly, notice how we're concatenating the string “Now longer!” onto the end of the string: vector<string> myVector(kNumStrings); for(vector<string>::iterator itr = myVector.begin(); itr != myVector.end(); ++itr) *itr += "Now longer!"; Despite the fact that string is an object, somehow C++ “knows” what it means to apply += to strings.
    [Show full text]
  • Dynamic Operator Overloading in a Statically Typed Language Olivier L
    Dynamic Operator Overloading in a Statically Typed Language Olivier L. Clerc and Felix O. Friedrich Computer Systems Institute, ETH Z¨urich, Switzerland [email protected], [email protected] October 31, 2011 Abstract Dynamic operator overloading provides a means to declare operators that are dispatched according to the runtime types of the operands. It allows to formulate abstract algorithms operating on user-defined data types using an algebraic notation, as it is typically found in mathematical languages. We present the design and implementation of a dynamic operator over- loading mechanism in a statically-typed object-oriented programming lan- guage. Our approach allows operator declarations to be loaded dynam- ically into a running system, at any time. We provide semantical rules that not only ensure compile-time type safety, but also facilitate the im- plementation. The spatial requirements of our approach scale well with a large number of types, because we use an adaptive runtime system that only stores dispatch information for type combinations that were encoun- tered previously at runtime. On average, dispatching can be performed in constant time. 1 Introduction Almost all programming languages have a built-in set of operators, such as +, -, * or /, that perform primitive arithmetic operations on basic data types. Operator overloading is a feature that allows the programmer to redefine the semantics of such operators in the context of custom data types. For that purpose, a set of operator implementations distinguished by their signatures has to be declared. Accordingly, each operator call on one or more custom-typed arguments will be dispatched to one of the implementations whose signature matches the operator's name and actual operand types.
    [Show full text]
  • CSE 307: Principles of Programming Languages Classes and Inheritance
    OOP Introduction Type & Subtype Inheritance Overloading and Overriding CSE 307: Principles of Programming Languages Classes and Inheritance R. Sekar 1 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Topics 1. OOP Introduction 3. Inheritance 2. Type & Subtype 4. Overloading and Overriding 2 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Section 1 OOP Introduction 3 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding OOP (Object Oriented Programming) So far the languages that we encountered treat data and computation separately. In OOP, the data and computation are combined into an “object”. 4 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Benefits of OOP more convenient: collects related information together, rather than distributing it. Example: C++ iostream class collects all I/O related operations together into one central place. Contrast with C I/O library, which consists of many distinct functions such as getchar, printf, scanf, sscanf, etc. centralizes and regulates access to data. If there is an error that corrupts object data, we need to look for the error only within its class Contrast with C programs, where access/modification code is distributed throughout the program 5 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Benefits of OOP (Continued) Promotes reuse. by separating interface from implementation. We can replace the implementation of an object without changing client code. Contrast with C, where the implementation of a data structure such as a linked list is integrated into the client code by permitting extension of new objects via inheritance. Inheritance allows a new class to reuse the features of an existing class.
    [Show full text]
  • A Summary of Operator Overloading Basic Idea
    A Summary of Operator Overloading David Kieras, EECS Dept., Univ. of Michigan Prepared for EECS 381 8/27/2013 Basic Idea You overload an operator in C++ by defining a function for the operator. Every operator in the language has a corresponding function with a name that is based on the operator. You define a function of this name that has at least one parameter of the class type, and returns a value of whatever type that you want. Because functions can have the same name if they have different signatures, the compiler will apply the correct operator function depending on the types in the call of it. Rule #1. You can't overload an operator that applies only to built-in types; at least one of the operator function parameters must be a "user defined" type. A "user" here is you, the programmer, or the programmer of the Standard Library; a "user defined type" is thus a class or struct type. This means you can't overload operator+ to redefine what it means to add two integers. Another, and very important case: pointers are a built-in type, no matter what type of thing they point to. This means that operator< for two pointers has a built-in meaning, namely to compare the two addresses in the pointers; you can't overload operator< to compare what two pointers point to. The Standard Library helps you work around this limitation. You define operator functions differently depending on whether the operator function is a member of your own type's class, or is a non-member function.
    [Show full text]
  • Types of Operators Description Arithmetic Operators These Are
    UNIT II OPERATORS Types of Operators Description These are used to perform mathematical calculations like addition, subtraction, Arithmetic_operators multiplication, division and modulus These are used to assign the values for Assignment_operators the variables in C programs. These operators are used to compare the Relational operators value of two variables. These operators are used to perform logical operations on the given two Logical operators variables. These operators are used to perform bit Bit wise operators operations on given two variables. Conditional operators return one value Conditional (ternary) if condition is true and returns another operators value is condition is false. These operators are used to either Increment/decrement increase or decrease the value of the operators variable by one. Special operators &, *, sizeof( ) and ternary operator ARITHMETIC OPERATORS IN C: C Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication, division and modulus in C programs. Arithmetic Operators/Operation Example + (Addition) A+B – (Subtraction) A-B * (multiplication) A*B / (Division) A/B % (Modulus) A%B EXAMPLE PROGRAM FOR C ARITHMETIC OPERATORS: // Working of arithmetic operators #include <stdio.h> int main() { int a = 9,b = 4, c; c = a+b; printf("a+b = %d \n",c); c = a-b; printf("a-b = %d \n",c); c = a*b; printf("a*b = %d \n",c); c = a/b; printf("a/b = %d \n",c); c = a%b; printf("Remainder when a divided by b = %d \n",c); return 0; } Output a+b = 13 a-b = 5 a*b = 36 a/b = 2 Remainder when a divided by b=1 Assignment Operators The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression.
    [Show full text]
  • Polymorphism
    Polymorphism A closer look at types.... Chap 8 polymorphism º comes from Greek meaning ‘many forms’ In programming: Def: A function or operator is polymorphic if it has at least two possible types. Polymorphism i) OverloaDing Def: An overloaDeD function name or operator is one that has at least two Definitions, all of Different types. Example: In Java the ‘+’ operator is overloaDeD. String s = “abc” + “def”; +: String * String ® String int i = 3 + 5; +: int * int ® int Polymorphism Example: Java allows user DefineD polymorphism with overloaDeD function names. bool f (char a, char b) { return a == b; f : char * char ® bool } bool f (int a, int b) { f : int * int ® bool return a == b; } Note: ML Does not allow function overloaDing Polymorphism ii) Parameter Coercion Def: An implicit type conversion is calleD a coercion. Coercions usually exploit the type-subtype relationship because a wiDening type conversion from subtype to supertype is always DeemeD safe ® a compiler can insert these automatically ® type coercions. Example: type coercion in Java Double x; x = 2; the value 2 is coerceD from int to Double by the compiler Polymorphism Parameter coercion is an implicit type conversion on parameters. Parameter coercion makes writing programs easier – one function can be applieD to many subtypes. Example: Java voiD f (Double a) { ... } int Ì double float Ì double short Ì double all legal types that can be passeD to function ‘f’. byte Ì double char Ì double Note: ML Does not perform type coercion (ML has no notion of subtype). Polymorphism iii) Parametric Polymorphism Def: A function exhibits parametric polymorphism if it has a type that contains one or more type variables.
    [Show full text]
  • Brief Overview of Python Programming Language
    Brief Overview Chapter of Python 3 In this chapter » Introduction to Python » Python Keywords “Don't you hate code that's not properly » Identifiers indented? Making it [indenting] part of » Variables the syntax guarantees that all code is » Data Types properly indented.” » Operators » Expressions — G. van Rossum » Input and Output » Debugging » Functions » if..else Statements » 3.1 INTRODUCTION TO PYTHON for Loop » Nested Loops An ordered set of instructions or commands to be executed by a computer is called a program. The language used to specify those set of instructions to the computer is called a programming language for example Python, C, C++, Java, etc. This chapter gives a brief overview of Python programming language. Python is a very popular and easy to learn programming language, created by Guido van Rossum in 1991. It is used in a variety of fields, including software development, web development, scientific computing, big data 2021-22 Chap 3.indd 31 19-Jul-19 3:16:31 PM 32 INFORMATICS PRACTICES – CLASS XI and Artificial Intelligence. The programs given in this book are written using Python 3.7.0. However, one can install any version of Python 3 to follow the programs given. Download Python 3.1.1 Working with Python The latest version of To write and run (execute) a Python program, we need Python is available on the to have a Python interpreter installed on our computer official website: or we can use any online Python interpreter. The https://www.python. interpreter is also called Python shell. A sample screen org/ of Python interpreter is shown in Figure 3.1.
    [Show full text]