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

Similar documents
Polymorphism. Zimmer CSCI 330

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

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

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

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

Polymorphism Part 1 1

C++ Programming: Polymorphism

C++ Important Questions with Answers

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

VIRTUAL FUNCTIONS Chapter 10

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

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

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

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

Object Oriented Programming. Solved MCQs - Part 2

What does it mean by information hiding? What are the advantages of it? {5 Marks}

C++ Inheritance and Encapsulation

Object-Oriented Programming, Iouliia Skliarova

Object-Oriented Programming, Iouliia Skliarova

POLYMORPHISM Polymorphism: the type Polymorphism taking many shapes type of object

04-24/26 Discussion Notes

Introduction to Programming Using Java (98-388)

Inheritance. Program construction in C++ for Scientific Computing. School of Engineering Sciences. Introduction. Michael Hanke.

COMP322 - Introduction to C++

Increases Program Structure which results in greater reliability. Polymorphism

Inheritance and aggregation

A <Basic> C++ Course

Inheritance, and Polymorphism.

Data Structures and Other Objects Using C++

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

Object Oriented Software Design II

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

CS 162, Lecture 25: Exam II Review. 30 May 2018

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

Object Oriented Software Design II

CS11 Introduction to C++ Fall Lecture 7

15: Polymorphism & Virtual Functions

OOP Fundamental Concepts

Chapter 5 Object-Oriented Programming

COMP322 - Introduction to C++ Lecture 09 - Inheritance continued

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Project. C++: Inheritance III. Plan. Project. Before we begin. The final exam. Advanced Topics. Project. This week in the home stretch

Object-Oriented Programming (OOP) Fundamental Principles of OOP

G52CPP C++ Programming Lecture 13

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

OBJECT ORIENTED PROGRAMMING USING C++

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

Inheritance, Polymorphism and the Object Memory Model

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

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

Chapter 15. Polymorphism and Virtual Functions. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Absolute C++ Walter Savitch

What are the characteristics of Object Oriented programming language?

COEN244: Polymorphism

Compaq Interview Questions And Answers

OOP THROUGH C++(R16) int *x; float *f; char *c;

Object-Oriented Programming

Midterm Exam 5 April 20, 2015

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

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

Inheritance and Polymorphism

Framework Fundamentals

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

Part VIII. More classes. Philip Blakely (LSC) C++ Introduction 226 / 370

C++ Inheritance II, Casting

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

Advanced C++ Topics. Alexander Warg, 2017

Polymorphism. Arizona State University 1

Virtual functions concepts

Common Misunderstandings from Exam 1 Material

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Inheritance and Polymorphism

Reusable and Extendable Code. Composition Example (1) Composition Example (2) CS183-Su'02-Lecture 8 17 June by Eric A. Durant, Ph.D.

Object Oriented Design

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

CPSC 427: Object-Oriented Programming

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

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

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

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

CPSC 427: Object-Oriented Programming

Passing arguments to functions by. const member functions const arguments to a function. Function overloading and overriding Templates

XII- COMPUTER SCIENCE VOL-II MODEL TEST I

Instantiation of Template class

CPSC 427: Object-Oriented Programming

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

Chapter 14 Abstract Classes and Interfaces

Short Notes of CS201

Object Oriented Programming: Inheritance Polymorphism

CS201 - Introduction to Programming Glossary By

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

Inheritance. Overview. Chapter 15 & additional topics. Inheritance Introduction. Three different kinds of inheritance

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

Inheritance and Polymorphism

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

Java: introduction to object-oriented features

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

C:\Temp\Templates. Download This PDF From The Web Site

Inheritance -- Introduction

step is to see how C++ implements type polymorphism, and this Exploration starts you on that journey.

Transcription:

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 (using classes) Class relationships (using inheritance) However, often upcasting does not offer the desired behavior Example class Car public: void start() cout << "Car::start()" << endl; } }; class BMW : public Car public: void start() cout << "BMW::start()" << endl; } }; int main(int argc, char** argv) Car *car = new BMW; car->start(); //Calls Car::start(), not BMW::start() delete car; } Example: intro.cpp 2

C++ Polymorphism Standard behavior The type of the pointer, not the type of the object determines the method to invoke Desired behavior The type of the object, not the type of the pointer should determine the method to invoke Concept called polymorphism Even if it looks the same (same pointer type), it may behave differently (different types of objects) Key concept for the understanding of object oriented programming 3

C++ Inheritance: Dynamic Binding Compiler decides at run-time which method is invoked Depending on the type pointed-at object Key-word virtual Example class Car virtual void start ()... } // Car::start }; class BMW : public Car virtual void start ()... } //Redefinition: BMW::start redefines Car::start }; Car *car; BMW *bmw; car = new Car; car->f(x); //Invokes Car::f bmw = new BMW; b->f(x); //Invokes BMW::f car = new BMW; //UPCAST!!! car->f(x); //Invokes BMW::f since the object s type is BMW Example: introvirtual.cpp 4

C++ Inheritance: Dynamic Binding Compiler adds type information to the classes data structures to determine the object s type at runtime Keyword virtual tells the compiler to not to perform static binding (only for virtual methods) Compilers implement this behind the scenes by adding vtables They list address offsets of virtual functions for this object Method invocations require additional level of indirection (performance) Derived Memory address Base Base TypeInfo Base* TypeInfo Derived* Base* 5

C++ Inheritance: Name hiding Recall Redefinition of non-virtual identifiers Virtual methods behave differently Not called redefinition, but overriding No different return types are allowed (to guarantee a common polymorphic interface) Exception Derived class may return Derived* instead of Base* 6

C++ Inheritance: Behavior in constructors Problem Derived classes have not been initialized while the in the constructor of the base class runs As a result, virtual functions can not be invoked as they might invoke non-initialized code Behavior In constructors, virtual methods of the current class are invoked Same applies to destructors 7

C++ Inheritance: Why is virtual an option? Why is virtual an option if it triggers the correct behavior? C++ philosophy: If you don t use, you don t pay for it Virtual function calls need slightly more performance Additional level of indirection through vtable Inhibits several other performance optimizations possible with static binding Don t be worried about efficiency in the first place When designing classes, use polymorphism (virtual) extensively Optimization is possible later if the class concept is designed well Example: exhaustiveexample.cpp 8

C++ Inheritance: Virtual destructors Objects are deleted from memory using pointers In conjunction with polymorphism, which destructor is called? Base* b = new Derived; b->do_something(); delete b; Same behavior as with non-virtual methods: Type of the pointer determines the function (here: destructor) invoked Classes using polymorphism (virtual) must implement virtual destructors class A public: virtual ~A() } virtual f() } } 9

C++ Inheritance: Designing interfaces Often, base classes only provide an interface and no functionality What is start() supposed to do for Vehicle or Car? Vehicle and Car provide the interface to the outside BMW and VW provide real functionality How to avoid implementing of such interface methods? Vehicle Car Lorry Bike BMW VW 10

C++ Inheritance: pure virtual methods C++ provides the concept of abstract classes Pure virtual methods have no implementation A class containing pure virtual methods can not be instantiated Abstract classes provide a common interface that sub-classes implement Syntax virtual method-signature = 0; Examples class A virtual void f() = 0; }; class B virtual void f(const int x&) const = 0; }; 11

C++ Inheritance: pure virtual methods Interface and implementation class Lamp public: virtual void on() = 0; virtual void off() = 0; }; Usage class LightBulb : public Lamp public: void on() } void off() } private: }; void switch_on(lamp& l) l.on(); } LightBulb lb; switch_on(lb); //Polymorphism LightBulb::on() Example: purevirtual.cpp 12

C++ Inheritance: Summary polymorphism Properties The type of the object pointed-at is important, not the type of the pointer Only for functions declared to be virtual Advantages Code (new behaviors) can be added without requiring changes to other classes Easy implementation of interfaces Disadvantages Dynamic binding introduces run-time overhead 13

C++ Inheritance: Object slicing Passing derived objects by reference or pointer is always safe f(base *b) } or f(base &b) } Derived d; f(&d); or f (d); OK, pointed-at object is still of type Derived Passing derived objects by value leads to object slicing f(base b) } Derived d; f(d); b is a copy of d of type Base (which may not be what you wanted) 14

C++ Inheritance: Down-Casting Sometimes its necessary to perform a safe down-cast Type* t = dynamic_cast<type*> variable; Returns NULL if the conversion was not possible Only applicable to pointers Introduces some runtime overhead Should not be used too often If used very often, there is a good chance of your design being flawed Example Vehicle *v = new BMW BMW* bmw = dynamic_cast<bmw*> v; VW* vw = dynamic_cast<vw*> v; if( bmw!= NULL ) } else if( vw!= NULL ) } 15