Inclusion Polymorphism

Size: px
Start display at page:

Download "Inclusion Polymorphism"

Transcription

1 06D-1 Inclusion Polymorphism Polymorphic code Polymorphic references Up- and Down- Casting Polymorphism and values Polymorphic Arrays

2 Inclusion Polymorphism in Context 06D-2 Polymorphism Ad hoc Universal Coercion Overloading Inclusion Sub-type Parametric Code Objects Inclusion, or subtype polymorphism arises from inheritance.

3 Inclusion Polymorphism and OOP In Strict Inheritance: SubclassingSubtyping 06D-3 Suppose that the function fire() expects an instance of class. Then, it will also accept an instance of class, provided that (strictly) inherits from. has everything has (in exactly the same form!) The additional operations in will not be used in fire() We say that the type is a subtype of the type. We say that the type includes the type. The polymorphism in this case is a result of subtyping, or type inclusion.

4 Methods are Polymorphic E; M; raise_salary 06D-4 E.raise_salary(10); // OK is_manager_of M.raise_salary(10); // OK E.is_manager_of(...); // Error M.is_manager_of(E); // OK The code of the raise_salary method is Polymorphic. It can be applied to all subtypes (subclasses) of. We see that without polymorphism, inheritance makes very little sense.

5 Polymorphic Objects 06D-5 All variables in Smalltalk are polymorphic. They may store instances of all classes. this is a polymorphic object. It may point to things of different subtypes at different times. A pointer to an inherited type is generated whenever an inherited method is called. In fact, all class pointers and all class references in C++ are polymorphic...

6 Pointers as Polymorphic Objects 06D-6 E, *pe; M, *pm; pe pm E M Rules for pointer mixing: pe = &E; // OK - Ordinary C type rules pm = &M; // OK - Ordinary C type rules pe = &M; // OK - Pointers are polymorphic! pm = &E; // Compile time error

7 References as Polymorphic Objects 06D-7 E M ostream& operator << ( ostream &, const & ); E; M; &eref1 = E; // OK! &eref2 = M; // OK! Reference to subobject &mref1 = E; // Compile time error! &mref2 = M; // OK! cout << E << M; // OK! Reference to subobject

8 Up-Casting Casting: A synonym for coercion from a derived type to the base type. Up-casting: casting pointers up the inheritance hierarchy. Up-casting of this occurs implicitly whenever an inherited method is called. raise_salary 06D-8 E; M; is_manager_of M.is_manager_of(E); // Type of this is *. // No casting occurs. M.raise_salary(10); // Type of this is * // in raise_salary. // Up casting must occur.

9 Down-Casting Down-Casting: casting pointers and references down the inheritance hierarchy: Must be done explicitly. Done by experts, and only in special cases. 06D-9 pe E E, *pe; M M, *pm; pe = &M; // OK: implicit upcasting. M = *pe; // Error: implicit downcasting is not allowed // explicit down casting: M = *( *)pe; // deprecated syntax M = *static_cast<*>pe; // recommended syntax // Either way, you better know what you are doing!

10 Safe Down-Casting RTTI: Run Time Type Identification New ANSI C++ compilers support RTTI. A programmer can add RTTI using an is_a function Messy! Given a pointer, it is possible to determine its dynamic type. Usually it is not necessary, and an indication of a bad design 06D-10 if ( *p = dynamic_cast< *>pe) { p->is_manager_of(e); } &eref = M;... &mref = dynamic_cast< &>eref; // bad_cast exception will be thrown if cast is invalid.

11 Value Semantics, Coercion & Polymorphism 06D-11 Polymorphism is applicable to code and variables but not to values. Coercion: translation from a value of one type to a value of a different type. Often with some loss of contents. Example: coercion from integer to real and vice versa. Inheritance in C++: defines a coercion from the derived class to the base class. The coercion is parametric! It works for all subtypes! Coercion is done by extracting the subobject.

12 What are Subobjects? 06D-12 class Base { //... }; class Derived: public Base { //... }; Each object of class Derived has a subobject of class Base It is possible in many cases to relate to that subobject

13 E M Mixing Values 06D-13 E; M; Rules for Mixing Values 1. call the (compiler generated) type casting operator from to 2. call the (compiler-defined or user-defined) to assignment operator. E = M; // OK - Valid coercion: truncation will occur. M = E; // Error - No coercion is defined. // is an but not vice-versa!

14 Arrays of Values 06D-14 Department[10]; Management[10]; Department and Management are not compatible in any way. In general, sizeof <= sizeof Usually, sizeof < sizeof Therefore, an array of managers (usually) occupies more space than an array of the same size of employees, and the conversion between the two is not trivial. This is just like an array of char which is not compatible at all with an array of int, although char and int are compatible in some operations.

15 Arrays of Pointers It is often convenient to define mixed type collections. The simplest and easiest way to do so is to use an array of pointers to the base class. 06D-15 *Department[100]; It is easy to deposit objects into the above array, however, determining the type of object that resides in a certain location requires down casting. Down casting should be used only in extremely special cases. In this common situation, what should be used instead is dynamic binding which is to be discussed in shortly.

Strict Inheritance. Object-Oriented Programming Spring 2008

Strict Inheritance. Object-Oriented Programming Spring 2008 Strict Inheritance Object-Oriented Programming 236703 Spring 2008 1 Varieties of Polymorphism P o l y m o r p h i s m A d h o c U n i v e r s a l C o e r c i o n O v e r l o a d i n g I n c l u s i o n

More information

Strict Inheritance. Object-Oriented Programming Winter

Strict Inheritance. Object-Oriented Programming Winter Strict Inheritance Object-Oriented Programming 236703 Winter 2014-5 1 1 Abstractions Reminder A class is an abstraction over objects A class hierarchy is an abstraction over classes Similar parts of different

More information

Inheritance & Polymorphism. Object-Oriented Programming Spring 2015

Inheritance & Polymorphism. Object-Oriented Programming Spring 2015 Inheritance & Polymorphism Object-Oriented Programming 236703 Spring 2015 1 1 Abstractions Reminder A class is an abstraction over objects A class hierarchy is an abstraction over classes Similar parts

More information

C++ Programming: Polymorphism

C++ Programming: Polymorphism C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both operators and functions can be overloaded

More information

Polymorphism. Zimmer CSCI 330

Polymorphism. Zimmer CSCI 330 Polymorphism Polymorphism - is the property of OOP that allows the run-time binding of a function's name to the code that implements the function. (Run-time binding to the starting address of the code.)

More information

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University Polymorphism Miri Ben-Nissan (Kopel) 1 Shape Triangle Rectangle Circle int main( ) Shape* p = GetShape( ); p->draw( ); Shape* GetShape( ) choose randomly which shape to send back For example: Shape* p

More information

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts.

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts. asting in C++: Bringing Safety and Smartness to Your Programs of 10 10/5/2009 1:20 PM By G. Bowden Wise The new C++ standard is full of powerful additions to the language: templates, run-time type identification

More information

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed? QUIZ Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed? Or Foo(x), depending on how we want the initialization

More information

CS105 C++ Lecture 7. More on Classes, Inheritance

CS105 C++ Lecture 7. More on Classes, Inheritance CS105 C++ Lecture 7 More on Classes, Inheritance " Operator Overloading Global vs Member Functions Difference: member functions already have this as an argument implicitly, global has to take another parameter.

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result. Every program uses data, either explicitly or implicitly to arrive at a result. Data in a program is collected into data structures, and is manipulated by algorithms. Algorithms + Data Structures = Programs

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Types. What is a type?

Types. What is a type? Types What is a type? Type checking Type conversion Aggregates: strings, arrays, structures Enumeration types Subtypes Types, CS314 Fall 01 BGRyder 1 What is a type? A set of values and the valid operations

More information

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding Conformance Conformance and Class Invariants Same or Better Principle Access Conformance Contract Conformance Signature Conformance Co-, Contra- and No-Variance Overloading and Overriding Inheritance as

More information

Inheritance and object compatibility

Inheritance and object compatibility Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not the other way around Examples: reference/pointer can

More information

Inheritance and aggregation

Inheritance and aggregation Advanced Object Oriented Programming Inheritance and aggregation Seokhee Jeon Department of Computer Engineering Kyung Hee University jeon@khu.ac.kr 1 1 Inheritance? Extend a class to create a new class

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,

More information

Topic 9: Type Checking

Topic 9: Type Checking Recommended Exercises and Readings Topic 9: Type Checking From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 13.17, 13.18, 13.19, 13.20, 13.21, 13.22 Readings: Chapter 13.5, 13.6 and

More information

Topic 9: Type Checking

Topic 9: Type Checking Topic 9: Type Checking 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 13.17, 13.18, 13.19, 13.20, 13.21, 13.22 Readings: Chapter 13.5, 13.6

More information

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

The Four Polymorphisms in C++ Subtype Polymorphism (Runtime Polymorphism) Polymorphism in C

The Four Polymorphisms in C++ Subtype Polymorphism (Runtime Polymorphism) Polymorphism in C The Four Polymorphisms in C++ When people talk about polymorphism in C++ they usually mean the thing of using a derived class through the base class pointer or reference, which is called subtype polymorphism.

More information

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

More information

Object Oriented Paradigm

Object Oriented Paradigm Object Oriented Paradigm History Simula 67 A Simulation Language 1967 (Algol 60 based) Smalltalk OO Language 1972 (1 st version) 1980 (standard) Background Ideas Record + code OBJECT (attributes + methods)

More information

Inheritance, Polymorphism and the Object Memory Model

Inheritance, Polymorphism and the Object Memory Model Inheritance, Polymorphism and the Object Memory Model 1 how objects are stored in memory at runtime? compiler - operations such as access to a member of an object are compiled runtime - implementation

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Casting in C++ (intermediate level)

Casting in C++ (intermediate level) 1 of 5 10/5/2009 1:14 PM Casting in C++ (intermediate level) Casting isn't usually necessary in student-level C++ code, but understanding why it's needed and the restrictions involved can help widen one's

More information

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University) Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202

More information

Concepts of Programming Languages

Concepts of Programming Languages Concepts of Programming Languages Lecture 10 - Object-Oriented Programming Patrick Donnelly Montana State University Spring 2014 Patrick Donnelly (Montana State University) Concepts of Programming Languages

More information

CPS 506 Comparative Programming Languages. Programming Language

CPS 506 Comparative Programming Languages. Programming Language CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support

More information

cast.c /* Program illustrates the use of a cast to coerce a function argument to be of the correct form. */

cast.c /* Program illustrates the use of a cast to coerce a function argument to be of the correct form. */ cast.c /* Program illustrates the use of a cast to coerce a function argument to be of the correct form. */ #include #include /* The above include is present so that the return type

More information

TPF Users Group Spring 2005

TPF Users Group Spring 2005 TPF Users Group Spring 2005 Get Ready For Standard C++! Name : Edwin W. van de Grift Venue : Applications Development Subcommittee AIM Enterprise Platform Software IBM z/transaction Processing Facility

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;

More information

CSE 431S Type Checking. Washington University Spring 2013

CSE 431S Type Checking. Washington University Spring 2013 CSE 431S Type Checking Washington University Spring 2013 Type Checking When are types checked? Statically at compile time Compiler does type checking during compilation Ideally eliminate runtime checks

More information

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions

More information

Chapter 5. Object- Oriented Programming Part I

Chapter 5. Object- Oriented Programming Part I Chapter 5 Object- Oriented Programming Part I 5: Preview basic terminology comparison of the Java and C++ approaches to polymorphic programming techniques introduced before in the context of inheritance:

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, 2 0 1 0 R E Z A S H A H I D I Today s class Constants Assignment statement Parameters and calling functions Expressions Mixed precision

More information

void fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) {

void fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) { TDDD38 APiC++ Exception Handling 134 Exception handling provides a way to transfer control and information from a point in the execution to an exception handler a handler can be invoked by a throw expression

More information

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction Lecture 13: Object orientation Object oriented programming Introduction, types of OO languages Key concepts: Encapsulation, Inheritance, Dynamic binding & polymorphism Other design issues Smalltalk OO

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

15: Polymorphism & Virtual Functions

15: Polymorphism & Virtual Functions 15: Polymorphism & Virtual Functions 김동원 2003.02.19 Overview virtual function & constructors Destructors and virtual destructors Operator overloading Downcasting Thinking in C++ Page 1 virtual functions

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 24, 2018 Outline Outline 1 Chapter 8: A C++ Introduction For Python Programmers Expressions and Operator Precedence

More information

Comp 311 Principles of Programming Languages Lecture 21 Semantics of OO Languages. Corky Cartwright Mathias Ricken October 20, 2010

Comp 311 Principles of Programming Languages Lecture 21 Semantics of OO Languages. Corky Cartwright Mathias Ricken October 20, 2010 Comp 311 Principles of Programming Languages Lecture 21 Semantics of OO Languages Corky Cartwright Mathias Ricken October 20, 2010 Overview I In OO languages, data values (except for designated non-oo

More information

Increases Program Structure which results in greater reliability. Polymorphism

Increases Program Structure which results in greater reliability. Polymorphism UNIT 4 C++ Inheritance What is Inheritance? Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Inheritance Consider a new type Square. Following how we declarations for the Rectangle and Circle classes we could declare it as follows:

More information

RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING QUESTION BANK UNIT I 2 MARKS

RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING QUESTION BANK UNIT I 2 MARKS RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING YEAR/SEM:II & III UNIT I 1) Give the evolution diagram of OOPS concept. 2) Give some

More information

2.1 Why did C need a ++?

2.1 Why did C need a ++? Chapter 2: Issues and Overview 2.1 Why did C need a ++? For application modeling. Shakespeare once explained it for houses, but it should be true of programs as well: When we mean to build, we first survey

More information

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

Design issues for objectoriented. languages. Objects-only pure language vs mixed. Are subclasses subtypes of the superclass? Encapsulation Encapsulation grouping of subprograms and the data they manipulate Information hiding abstract data types type definition is hidden from the user variables of the type can be declared variables

More information

Object-oriented Programming. Object-oriented Programming

Object-oriented Programming. Object-oriented Programming 2014-06-13 Object-oriented Programming Object-oriented Programming 2014-06-13 Object-oriented Programming 1 Object-oriented Languages object-based: language that supports objects class-based: language

More information

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017 OOP components For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Data Abstraction Information Hiding, ADTs Encapsulation Type Extensibility Operator Overloading

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Introduction to Object-Oriented Programming Review 2: Object-Oriented Programming Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Review 2: Object-Oriented Programming 1 / 14 Topics

More information

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Casting and polymorphism Enumeration

Casting and polymorphism Enumeration Casting and polymorphism Enumeration Shahram Rahatlou http://www.roma1.infn.it/people/rahatlou/programmazione++/ Corso di Programmazione++ Roma, 25 May 2009 1 Polymorphic vector of Person vector

More information

From IMP to Java. Andreas Lochbihler. parts based on work by Gerwin Klein and Tobias Nipkow ETH Zurich

From IMP to Java. Andreas Lochbihler. parts based on work by Gerwin Klein and Tobias Nipkow ETH Zurich From IMP to Java Andreas Lochbihler ETH Zurich parts based on work by Gerwin Klein and Tobias Nipkow 2015-07-14 1 Subtyping 2 Objects and Inheritance 3 Multithreading 1 Subtyping 2 Objects and Inheritance

More information

Overloading המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Overloading המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון Overloading עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Roadmap In this chapter we will investigate the idea of overloading: Overloading based on scopes Overloading based on type signatures Coercion,

More information

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

Lecture Notes on Programming Languages

Lecture Notes on Programming Languages Lecture Notes on Programming Languages 85 Lecture 09: Support for Object-Oriented Programming This lecture discusses how programming languages support object-oriented programming. Topics to be covered

More information

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED. Constructor and Destructor Member Functions Constructor: - Constructor function gets invoked automatically when an object of a class is constructed (declared). Destructor:- A destructor is a automatically

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling Line 5 11 this.x

More information

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can

More information

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Modern Programming Languages. Lecture Java Programming Language. An Introduction Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Const correctness What is const correctness? It is a semantic constraint, enforced

More information

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini bertini@dsi.unifi.it http://www.dsi.unifi.it/~bertini/ Const correctness What is const correctness? It is a semantic constraint, enforced

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

Note 3. Types. Yunheung Paek. Associate Professor Software Optimizations and Restructuring Lab. Seoul National University

Note 3. Types. Yunheung Paek. Associate Professor Software Optimizations and Restructuring Lab. Seoul National University Note 3 Types Yunheung Paek Associate Professor Software Optimizations and Restructuring Lab. Seoul National University Topics Definition of a type Kinds of types Issues on types Type checking Type conversion

More information

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 5 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Templates S Function and class templates you specify with a single code segment an entire

More information

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance Handout written by Julie Zelenski, updated by Jerry. Inheritance is a language property most gracefully supported by the object-oriented

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms AUTO POINTER (AUTO_PTR) //Example showing a bad situation with naked pointers void MyFunction()

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak! //Example showing a bad situation with naked pointers CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING 2011 C ++ Basics Review part 2 Auto pointer, templates, STL algorithms void MyFunction() MyClass* ptr( new

More information

Fundamentals of Programming Languages

Fundamentals of Programming Languages Fundamentals of Programming Languages 1. DEFINITIONS... 2 2. BUILT-IN TYPES AND PRIMITIVE TYPES... 3 TYPE COMPATIBILITY... 9 GENERIC TYPES... 14 MONOMORPHIC VERSUS POLYMORPHIC... 16 TYPE IMPLEMENTATION

More information

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : M.Sc CST Semester / Year : EVEN / II Subject Name

More information

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck

C++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck C++ Crash Kurs Polymorphism Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ Polymorphism Major abstractions of C++ Data abstraction

More information

IS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class

IS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class IS0020 Program Design and Software Tools Summer, 2004 August 2, 2004 in Class Name: A. Fill in the blanks in each of the following statements [Score: 20]: 1. A base class s members can be accessed only

More information

Subtyping. Lecture 13 CS 565 3/27/06

Subtyping. Lecture 13 CS 565 3/27/06 Subtyping Lecture 13 CS 565 3/27/06 Polymorphism Different varieties of polymorphism: Parametric (ML) type variables are abstract, and used to encode the fact that the same term can be used in many different

More information

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a. Intro to OOP - Object and class - The sequence to define and use a class in a program - How/when to use scope resolution operator - How/when to the dot operator - Should be able to write the prototype

More information

Resource Management With a Unique Pointer. Resource Management. Implementing a Unique Pointer Class. Copying and Moving Unique Pointers

Resource Management With a Unique Pointer. Resource Management. Implementing a Unique Pointer Class. Copying and Moving Unique Pointers Resource Management Resource Management With a Unique Pointer Dynamic memory is an example of a resource that is allocated and must be released. void f() { Point* p = new Point(10, 20); // use p delete

More information

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

More information

Object typing and subtypes

Object typing and subtypes CS 242 2012 Object typing and subtypes Reading Chapter 10, section 10.2.3 Chapter 11, sections 11.3.2 and 11.7 Chapter 12, section 12.4 Chapter 13, section 13.3 Subtyping and Inheritance Interface The

More information

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1 Object-Oriented Languages and Object-Oriented Design Ghezzi&Jazayeri: OO Languages 1 What is an OO language? In Ada and Modula 2 one can define objects encapsulate a data structure and relevant operations

More information

25. Generic Programming

25. Generic Programming 25. Generic Programming Java Fall 2009 Instructor: Dr. Masoud Yaghini Generic Programming Outline Polymorphism and Generic Programming Casting Objects and the instanceof Operator The protected Data and

More information

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p. Preface to the Second Edition p. iii Preface to the First Edition p. vi Brief Contents p. ix Introduction to C++ p. 1 A Review of Structures p. 1 The Need for Structures p. 1 Creating a New Data Type Using

More information

CS304 Object Oriented Programming

CS304 Object Oriented Programming 1 CS304 Object Oriented Programming 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes?

More information

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

Week 7. Statically-typed OO languages: C++ Closer look at subtyping C++ & Subtyping Week 7 Statically-typed OO languages: C++ Closer look at subtyping Why talk about C++? C++ is an OO extension of C Efficiency and flexibility from C OO program organization from Simula

More information

Improving Enumeration Types [N1513= ] David E. Miller

Improving Enumeration Types [N1513= ] David E. Miller Introduction Improving Enumeration Types [N1513=03-0096] David E. Miller It has been said, "C enumerations constitute a curiously half-baked concept." [Design and Evolution of C++ (C) 1994, B.Stroustrup,

More information

September 10,

September 10, September 10, 2013 1 Bjarne Stroustrup, AT&T Bell Labs, early 80s cfront original C++ to C translator Difficult to debug Potentially inefficient Many native compilers exist today C++ is mostly upward compatible

More information

Does anyone actually do this?

Does anyone actually do this? Session 11: Polymorphism Coding type-dependent logic Virtual functions Pure virtual functions and abstract classes Coding type-dependent logic Suppose we need to do something different depending on what

More information

CS152: Programming Languages. Lecture 23 Advanced Concepts in Object-Oriented Programming. Dan Grossman Spring 2011

CS152: Programming Languages. Lecture 23 Advanced Concepts in Object-Oriented Programming. Dan Grossman Spring 2011 CS152: Programming Languages Lecture 23 Advanced Concepts in Object-Oriented Programming Dan Grossman Spring 2011 So far... The difference between OOP and records of functions with shared private state

More information

Chapter 2: Java OO II X I A N G Z H A N G

Chapter 2: Java OO II X I A N G Z H A N G Chapter 2: Java OO II X I A N G Z H A N G j a v a c o s e @ q q. c o m Content 2 Abstraction Abstract Class Interface Inheritance Polymorphism Abstraction What is Abstraction? Abstraction 4 An abstraction

More information

Department of Computer science and Engineering Sub. Name: Object oriented programming and data structures Sub. Code: EC6301 Sem/Class: III/II-ECE Staff name: M.Kavipriya Two Mark Questions UNIT-1 1. List

More information