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

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

15: Polymorphism & Virtual Functions

Object-Oriented Programming

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors

Inheritance, Polymorphism and the Object Memory Model

Polymorphism. Zimmer CSCI 330

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

Polymorphism Part 1 1

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

C++ Important Questions with Answers

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

QUIZ. What is wrong with this code that uses default arguments?

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

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

C++ Programming: Polymorphism

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

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

Virtual functions concepts

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

Ch. 11: References & the Copy-Constructor. - continued -

VIRTUAL FUNCTIONS Chapter 10

QUIZ Friends class Y;

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

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

Absolute C++ Walter Savitch

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

Polymorphism. Hsuan-Tien Lin. OOP Class, April 8, Department of CSIE, NTU. H.-T. Lin (NTU CSIE) Polymorphism OOP 04/08/ / 26

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

Inheritance, Polymorphism, and Interfaces

04-24/26 Discussion Notes

Java Object Oriented Design. CSC207 Fall 2014

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

Object-Oriented Programming, Iouliia Skliarova

Data Abstraction. Hwansoo Han

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Cpt S 122 Data Structures. Course Review FINAL. Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University

Lecturer: William W.Y. Hsu. Programming Languages

CPS 506 Comparative Programming Languages. Programming Language

Chapter 5 Object-Oriented Programming

Object Oriented Software Design II

Upcasting. Taking an object reference and treating it as a reference to its base type is called upcasting.

CS11 Introduction to C++ Fall Lecture 7

Polymorphism and Inheritance

Object Oriented Software Design II

Object Oriented Programming with c++ Question Bank

CS-202 Introduction to Object Oriented Programming

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Increases Program Structure which results in greater reliability. Polymorphism

1: Introduction to Object (1)

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

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

QUIZ How do we implement run-time constants and. compile-time constants inside classes?

Inheritance STL. Entity Component Systems. Scene Graphs. Event Systems

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

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

Dynamic Binding C++ Douglas C. Schmidt

Lecture Notes on Programming Languages

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

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

This wouldn t work without the previous declaration of X. This wouldn t work without the previous declaration of y

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

Data Structures (list, dictionary, tuples, sets, strings)

Inheritance. Chapter 15 & additional topics

Software Design and Analysis for Engineers

First IS-A Relationship: Inheritance

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

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

More Relationships Between Classes

CIS 190: C/C++ Programming. Lecture 11 Polymorphism

Chapter 1: Object-Oriented Programming Using C++

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Inclusion Polymorphism

CMSC202 Computer Science II for Majors

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

What are the characteristics of Object Oriented programming language?

G52CPP C++ Programming Lecture 13

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

Instantiation of Template class

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?

Object-Oriented Concept

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

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

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

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

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

Overview. Constructors and destructors Virtual functions Single inheritance Multiple inheritance RTTI Templates Exceptions Operator Overloading

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

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

Concepts of Programming Languages

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

What is Inheritance?

The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis

OBJECT ORIENTED PROGRAMMING USING C++

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

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

CS 251 Intermediate Programming Inheritance

Inheritance Ch

Transcription:

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 to be made.

Criticize!

Ch. 15: Polymorphism & Virtual Functions

text Virtual functions enhance the concept of type. There is no analog to the virtual function in a traditional procedural language. As a procedural programmer, you have no referent with which to think about virtual functions, as you do with almost every other feature in the language. Features in a procedural language can be understood on an algorithmic level, but, in an OOL, virtual functions can be understood only from a design viewpoint.

Remember upcasting

Draw the UML diagram!

We would like the more specific version of play() to be called, since flute is a Wind object, not a generic Instrument.

Ch. 1: Introduction to Objects Remember from ch.1

text Early binding vs. late binding The C++ compiler inserts a special bit of code in lieu of the absolute call. This code calculates the address of the function body, using information stored in the object at runtime!

Ch. 15: Polymorphism & Virtual Functions

text virtual functions To cause late binding to occur for a particular function, C++ requires that you use the virtual keyword when declaring the function in the base class. All derived-class functions that match the signature of the base-class declaration will be called using the virtual mechanism. example

It is legal to also use the virtual keyword in the derived-class declarations, but it is redundant and can be confusing.

text Extensibility With play( ) defined as virtual in the base class, you can add as many new types as you want without changing the tune( ) function. In a well-designed OOP program, most or all of your functions will follow the model of tune( ) and communicate only with the base-class interface. Such a program is extensible because [ ] the functions that manipulate the base-class interface will not need to be changed at all to accommodate the new classes.

Read and understand the full program C15:Instrument4.cpp

text How C++ implements late binding The typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual functions for that particular class in the VTABLE. In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object.

If function is not overridden in the base class, the address of its base-class version is placed in the VTABLE.

Here s what a call to adjust( ) for a Brass object looks like, if made through an Instrument pointer: (An Instrument reference produces the same result) The memory overhead is only one pointer, no matter how many virtual functions there are!

Installing the vpointer This is where the default constructor is essential: In the Instrument examples, the compiler creates a default constructor that does nothing except initialize VPTR. This constructor, of course, is automatically called for all Instrument objects before you can do anything with them, so you know that it s always safe to call virtual functions.

Objects are different early binding? and references? [ ] upcasting deals only with addresses (?) Means: Upcasting is not necessarily implemented by the compiler via late binding. Actually, if given the choice, the compiler will probably prefer early binding, since it results in faster code. But when the compiler does not have the object (i.e. when the object is passed by pointer or reference), it must use late binding. Code example

Abstract base classes and pure virtual functions Often in a design, you want the base class to present only an interface for its derived classes. That is, you don t want anyone to actually create an object of the base class, only to upcast to it so that its interface can be used. We say that the virtual function is pure.

A class with only pure virtual functions is called a pure abstract class. These functions exist only to create a common interface for all the derived classes. Code example

The compiler still reserves a slot for a pure virtual function in the VTABLE, but does not to put an address in that particular slot.

QUIZ Write a pure virtual function foo in the parent class, and redefine it as a virtual function in the child class.

QUIZ In practical terms, what is the difference between a virtual function and a pure virtual one?

Solution In practical terms, what is the difference between a virtual function and a pure virtual one? A: If a class has a pure virtual function, no objects of that class can be instantiated.

QUIZ Does this code compile? (Assume that Abstract::bar and Derived::foo are defined in another file.) int main(){ Derived d; } Source: http://stackoverflow.com/questions/8931612/do-all-virtual-functions-need-to-be-implemented-in-derived-classes

Solution Yes. A derived class does not need to override virtual functions from the parent, only pure virtual ones! int main(){ Derived d; }

Actually, not every derived class needs to override the pure virtuals from the parent! A function can stay pure virtual in several levels of the hierarchy. (But, eventually, all pure virtuals must be overriden in order to be able to instantiate objects.) int main(){ DerivedMore dm; }

Virtual functions in multi-level hierarchies

Individual work for next time: Read and understand the section Under the hood Why virtual functions? End-of-chapter exercise 1 EOL 1

QUIZ How is the late binding of virtual functions implemented in the C++ compiler?

text How C++ implements late binding The typical compiler creates a single table (called the VTABLE) for each class that contains virtual functions. The compiler places the addresses of the virtual functions for that particular class in the VTABLE. In each class with virtual functions, it secretly places a pointer, called the vpointer (abbreviated as VPTR), which points to the VTABLE for that object.

QUIZ Why do we need virtual functions?

text virtual functions To cause late binding and upcasting to occur for a particular function, C++ requires that you use the virtual keyword when declaring the function in the base class. All derived-class functions that match the signature of the base-class declaration will be called using the virtual mechanism.

QUIZ Why do we need pure virtual functions?

Abstract base classes and pure virtual functions Often in a design, you want the base class to present only an interface for its derived classes. That is, you don t want anyone to actually create an object of the base class, only to upcast to it so that its interface can be used. We say that the virtual function is pure.

Common misconception: It s illegal to provide a definition for a pure virtual function But, wait a second: If we cannot instantiate objects of type Abstract, what use can the definition be?

It is legal to provide a definition for a pure virtual function! We can always access the parent function using the scope resolution operator!

however, the pure virtual function definition cannot be inline:

QUIZ: Show how to access the Pet pure virtual code in main

Inheritance and the VTABLE It is also possible to add new virtual functions to the derived class. example

VTABLEs created by the compiler for Pet and Dog:

VTABLEs created by the compiler for Pet and Dog: Problem: We cannot use sit() with an upcast pointer or reference!

This is the opposite of upcasting It is called downcasting.

Solution: typecast manually!

Extra-credit quiz

Ch. 3: The C in C++

C++ explicit casts Back to Ch.15

Run-time type identification (RTTI) RTTI is all about casting base-class pointers down to derived-class pointers ( up and down are relative to a typical class diagram, with the base class at the top). Casting up happens automatically, with no coercion, because it s completely safe. Casting down is unsafe because there s no compile time information about the actual types, so you must know exactly what type the object is. If you cast it into the wrong type, you ll be in trouble.

Run-time type identification (RTTI) dynamic_cast does its work at runtime, using the virtual table It tends to be more expensive than the other C++-style casts.

QUIZ Is this use of the function sit( ) correct? Explain.

Solution Is this use of the function sit() correct? Explain. Yes. Remember that, when the compiler has the actual object, it uses early binding, so the VTABLE never comes into play.

Polymorphism - definition It is the virtual function mechanism described in this chapter, involving the VTABLE, VPTRs, upcasting, downcasting and RTTI. It allows late binding to occur.

Object slicing or Why we should not use pass-byvalue with polymorphism

Do you remember how parameters are passed to a function? An object the size of Pet is pushed on the stack (and cleaned up after the call)

Fluffy is sliced

Do. Not. Slice. Fluffy. Object slicing actually removes part of the object as it copies it into the new object (rather than simply changing the meaning of an address, as when using a pointer or reference). Because of this, upcasting into an object is not done often; in fact, it s usually something to watch out for and prevent.

Overloading & overriding In Chapter 14, we learned that redefining an overloaded function in the base class hides all of the other base-class versions of that function. When virtual functions are involved the behavior is a little different.

The base class is expecting an int to be returned from f( ). The derived-class version of f( ) must keep that contract!

Does this mean that we cannot modify the return type of a virtual function during overriding?

In general, yes! Does this mean that we cannot modify the return type of a virtual function during overriding? but there is a special case in which we can slightly modify the return type: If returning a pointer or a reference to a base class, the overridden version of the function may return a pointer or reference to a class derived from that base. This is called

Variant return type Note: Returning the base type will generally solve your problems so this is a rather specialized feature. This is another application of dynamic_cast!

Same as in base class, no new rule need aply. Draw the UML class diagram! The variant type rule allows this: The return type is more derived than in the base class (but inherited from it!!)

Example user code No problem, the two types agree. Need a downcast (less safe!)

We stop before the section virtual functions & constructors and we skip the remainder of this chapter. Individual work / review for Ch.15: End-of-chapter exercises 2, 3 EOL 2