Polymorphism. Arizona State University 1

Similar documents
COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

Inheritance and Polymorphism

Inheritance and Polymorphism

Chapter 15: Inheritance, Polymorphism, and Virtual Functions

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

Polymorphism. Zimmer CSCI 330

VIRTUAL FUNCTIONS Chapter 10

Inheritance and Polymorphism

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

CS111: PROGRAMMING LANGUAGE II

Chapter 14 Abstract Classes and Interfaces

Object-Oriented Programming

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

Object-Oriented Programming More Inheritance

Introduction to Object-Oriented Programming

OBJECT ORIENTED PROGRAMMING. Abstract Class And Interface

15: Polymorphism & Virtual Functions

Make Classes Useful Again

What is Inheritance?

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

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

Static and Dynamic Behavior לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

ECE 122. Engineering Problem Solving with Java

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

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

Chapter 5 Object-Oriented Programming

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Programming II (CS300)

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

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

OVERRIDING. 7/11/2015 Budditha Hettige 82

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Instantiation of Template class

Inheritance and object compatibility

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

CS 403/503 Exam 4 Spring 2015 Solution

Critique this Code. Hint: It will crash badly! (Next slide please ) 2011 Fawzi Emad, Computer Science Department, UMCP

Lecture Notes on Programming Languages

C++ Programming: Polymorphism

First IS-A Relationship: Inheritance

Object Oriented Programming with c++ Question Bank

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

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

Functions. Arizona State University 1

MAHALAKSHMI ENGINEERING COLLEGE B TIRUCHIRAPALLI

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

CS 251 Intermediate Programming Inheritance

C++ Important Questions with Answers

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

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

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

Interface Class. Lecture 22. Based on Slides of Dr. Norazah Yusof

26. Interfaces. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

COMP322 - Introduction to C++

Introduction to Programming

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

ECE 3574: Dynamic Polymorphism using Inheritance

More Relationships Between Classes

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

CSA 1019 Imperative and OO Programming

Object Oriented Design

Object-Oriented Design (OOD) and C++

Method Resolution Approaches. Dynamic Dispatch

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

Static and Dynamic Behavior עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מובסס על הרצאות של אותו קורס שניתן בשנים הקודמות ע "י ד"ר גרא וייס

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Solved MCQs - Part 2

Exceptions, Templates, and the STL

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Why use inheritance? The most important slide of the lecture. Programming in C++ Reasons for Inheritance (revision) Inheritance in C++

Java Object Oriented Design. CSC207 Fall 2014

Inheritance, polymorphism, interfaces

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Chapter 10: Inheritance

Practice for Chapter 11

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

type conversion polymorphism (intro only) Class class

C++ Inheritance and Encapsulation

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

[ L5P1] Object-Oriented Programming: Advanced Concepts

Data Abstraction. Hwansoo Han

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Polymorphism Part 1 1

Pointers! Arizona State University 1

Extending Classes (contd.) (Chapter 15) Questions:

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

Ch02. True/False Indicate whether the statement is true or false.

Object-Oriented ProgrammingInheritance & Polymorphism

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

KLiC C++ Programming. (KLiC Certificate in C++ Programming)

COMP 110/L Lecture 20. Kyle Dewey

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Transcription:

Polymorphism CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 15 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University 1

Type Compatibility wrt Inheritance Classes in a program may be part of an inheritance hierarchy Animal Cat Dog Classes lower in the hierarchy are special cases of those above Poodle Arizona State University 2

Type Compatibility wrt Inheritance (cont.) A pointer to a derived class can be assigned to a pointer to a base class. Another way to say this is: A base class pointer can point to derived class objects Animal *pa = new Cat; Arizona State University 3

Type Compatibility wrt Inheritance (cont.) Assigning a base class pointer to a derived class pointer requires a cast Animal *pa = new Cat; Cat *pc; pc = static_cast<cat *>(pa); The base class pointer must already point to a derived class object for this to work correctly. Arizona State University 4

Using Type Casts C++ uses the declared type of a pointer to determine access to the members of the pointed-to object If an object of a derived class is pointed to by a base class pointer, all members of the derived class may not be accessible Type cast the base class pointer to the derived class (via static_cast) in order to access members that are specific to the derived class Arizona State University 5

Polymorphism + Virtual Functions Polymorphic code: Code that behaves differently when it acts on objects of different types Virtual Member Function: The C++ mechanism for achieving polymorphism Consider the Animal, Cat, Dog hierarchy where each class has its own version of the member function id( ) class Animal{ void id(){cout << "animal";} } class Cat : public Animal{ void id(){ cout << "cat";} } class Dog : public Animal{ void id(){ cout << "dog"; } } Arizona State University 6

Polymorphism Consider the collection of different Animal objects Animal *pa[] = {new Animal, new Dog, new Cat}; and accompanying code for(int k=0; k<3; k++) pa[k]->id(); Prints: animal animal animal, ignoring the more specific versions of id() in Dog and Cat Arizona State University 7

Polymorphism (cont.) The preceding code is not polymorphic: it behaves the same way even though Animal, Dog and Cat have different types and different id() member functions Polymorphic code would have printed "animal dog cat" instead of "animal animal animal" The code is not polymorphic because in the expression pa[k]->id() the compiler sees only the type of the pointer pa[k], which is pointer to Animal Compiler does not see type of actual object pointed to, which may be Animal, or Dog, or Cat Arizona State University 8

Virtual Functions Declaring a function virtual will make the compiler check the type of each object to see if it defines a more specific version of the virtual function If the member functions id()are declared virtual, then the code Animal *pa[] = {new Animal, new Dog,new Cat}; for(int k=0; k<3; k++) pa[k]->id(); will print animal dog cat Arizona State University 9

Virtual Function Example How to declare a member function virtual: class Animal{ public: virtual void id(){cout << "animal";} } class Cat : public Animal{ public: virtual void id(){cout << "cat";} } class Dog : public Animal{ public: virtual void id(){cout << "dog";} } Arizona State University 10

Function Binding In pa[k]->id(), Compiler must choose which version of id() to use: There are different versions in the Animal, Dog, and Cat classes Function binding is the process of determining which function definition to use for a particular function call The alternatives are static and dynamic binding Arizona State University 11

Static vs. Dynamic Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually pointed to Static binding is done at compile time Dynamic Binding determines the function to be invoked at execution time Can look at the actual class of the object pointed to and choose the most specific version of the function Dynamic binding is used to bind virtual functions Arizona State University 12

Overriding vs. Overloading Recall that Overloaded functions have the same name but different parameter lists. If a base class has a virtual member function and a derived class has an overloading member function, use the override key word at the end of the function header or prototype to indicate that it should be treated as an overriding function. Arizona State University 13

final + Overriding The key word final can be used at the end of the header or prototype of a function in an inheritance hierarchy if you want to ensure that no classes below this one override this function. If an attempt is made to override this function in a derived class, a compiler error will occur. Arizona State University 14

Abstract Class An abstract class is a class that contains no objects that are not members of subclasses (derived classes) For example, in real life, Animal is an abstract class: there are no animals that are not dogs, or cats, or lions Abstract classes are an organizational tool. They are useful in organizing inheritance hierarchies Abstract classes can be used to specify an interface that must be implemented by all subclasses Arizona State University 15

Abstract Functions The member functions specified in an abstract class do not have to be implemented The implementation is left to the subclasses In C++, an abstract class is a class with at least one abstract member function Arizona State University 16

Pure Virtual Functions In C++, a member function of a class is declared to be an abstract function by making it virtual and replacing its body with = 0; class Animal{ public: virtual void id()=0; }; A virtual function with its body omitted and replaced with =0 is called a pure virtual function, or an abstract function Arizona State University 17

More on Abstract Classes An abstract class can not be instantiated An abstract class can only be inherited from; that is, you can derive classes from it Classes derived from abstract classes must override all pure virtual functions with concrete member functions before they can be instantiated. Arizona State University 18

Composition vs. Inheritance Inheritance models an 'is a' relation between classes. An object of a derived class 'is a(n)' object of the base class Example: an UnderGrad is a Student a Mammal is an Animal a Poodle is a Dog Arizona State University 19

Composition vs. Inheritance (cont.) When defining a new class: Composition is appropriate when the new class needs to use an object of an existing class Inheritance is appropriate when objects of the new class are a subset of the objects of the existing class, or objects of the new class will be used in the same ways as the objects of the existing class Arizona State University 20