Introduction to inheritance

Similar documents
Problem: Given a vector of pointers to Shape objects, print the area of each of the shape.

Programming in C# Inheritance and Polymorphism

Inheritance (Deitel chapter 9)

Inheritance Motivation

Object Oriented Programming. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 27 December 8, What is a class? Extending a Hierarchy

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

JAVA Programming Language Homework V: Overall Review

Chapter 9 - Object-Oriented Programming: Inheritance

Inheritance Introduction. 9.1 Introduction 361

A A B U n i v e r s i t y

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

Java 程式設計入門. 講師 : 陳昭源 CSIE, NTU September 28, 2005

Object Oriented Programming. Java-Lecture 11 Polymorphism

Polymorphism. Arizona State University 1

C++ Inheritance and Encapsulation

Lecture 5: Inheritance

CHAPTER 6 Class-Advanced Concepts - Inheritance

Inheritance, and Polymorphism.

Chapter 19 - C++ Inheritance

VIRTUAL FUNCTIONS Chapter 10

Java 程式設計基礎班 (7) 莊坤達台大電信所網路資料庫研究室. Java I/O. Class 7 1. Class 7 2

Programming Languages: OO Paradigm, Polymorhism and Class Members

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

Object Oriented Software Design II

Object Oriented Software Design II

Fig. 9.1 Fig. 9.2 Fig. 9.3 Fig. 9.4 Fig. 9.5 Fig. 9.6 Fig. 9.7 Fig. 9.8 Fig. 9.9 Fig Fig. 9.11

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

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

Chapter 20 - C++ Virtual Functions and Polymorphism

15: Polymorphism & Virtual Functions

Chapter 19 C++ Inheritance

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

Polymorphism. Zimmer CSCI 330

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

Object Oriented Programming

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

Chapter 14 Abstract Classes and Interfaces

Polymorphism Part 1 1

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

COMP322 - Introduction to C++

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

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

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

C++ Programming: Polymorphism

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

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

CS111: PROGRAMMING LANGUAGE II

CST242 Object-Oriented Programming Page 1

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

Oxford isolution. 下載及安裝指南 Download and Installation Guide

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

25. Generic Programming

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

Inheritance CSC9Y4. Inheritance

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Inheritance and Polymorphism

虛擬機 - 惡意程式攻防的新戰場. 講師簡介王大寶, 小時候大家叫他王小寶, 長大後就稱王大寶, 目前隸屬一神祕單位. 雖然佯稱興趣在看書與聽音樂, 但是其實晚上都在打 Game. 長期於系統最底層打滾, 熟悉 ASM,C/C++,

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

ECE 3574: Dynamic Polymorphism using Inheritance

Chapter 4 (Part IV) The Processor: Datapath and Control (Parallelism and ILP)

Inheritance and Polymorphism

Inheritance and object compatibility

Cpt S 122 Data Structures. Inheritance

Inheritance and Polymorphism

Inheritance and aggregation

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

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

Midterm Exam 5 April 20, 2015

Object-Oriented Programming, Iouliia Skliarova

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

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

Subtyping (Dynamic Polymorphism)

Inheritance and Overloading. Week 11

CS111: PROGRAMMING LANGUAGE II

Citrix CloudGateway. aggregate control. all apps and data to any device, anywhere

桌上電腦及筆記本電腦安裝 Acrobat Reader 應用程式

Inheritance, Polymorphism, and Interfaces

Francesco Nidito. Programmazione Avanzata AA 2007/08

Inheritance and Polymorphism

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Francesco Nidito. Programmazione Avanzata AA 2007/08

Polymorphism and Interfaces. CGS 3416 Spring 2018

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

IS 0020 Program Design and Software Tools

BBM 102 Introduction to Programming II Spring Inheritance

Chapter 2 (Part 2) Instructions: Language of the Computer

8. Polymorphism and Inheritance

臺北巿立大學 104 學年度研究所碩士班入學考試試題

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

2009 OB Workshop: Structural Equation Modeling. Changya Hu, Ph.D. NCCU 2009/07/ /07/03

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

COEN244: Polymorphism

Object-Oriented Programming

Java Object Oriented Design. CSC207 Fall 2014

Figure 1 Microsoft Visio

CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC

Object. OutputStream write(int) write(byte[]) write(byte[], int, int) FilterOutputStream write(int) write(byte[]) write(byte[], int, int)

Data Abstraction. Hwansoo Han

Transcription:

C++ Inheritance and Polymorphism CSIE Department, NTUT Woei-Kae Chen 1 Introduction to inheritance Inheritance Derived class inherits data members and member functions from base class Single inheritance inherits from one base class Multiple inheritance inherits from multiple base classes Types of inheritance public private protected Is a relationship Alternative to composition Base Derived 2 1

Inheritance Examples 1 Base class Student Shape Loan Employee Account Derived classes GraduateStudent UndergraduateStudent Circle Triangle Rectangle CarLoan HomeImprovementLoan MortgageLoan FacultyMember StaffMember CheckingAccount SavingsAccount 3 Inheritance Examples 2 Base class ( 或 super class) CommunityMember Employee Student Alumnus Single inheritance Faculty Staff Single inheritance Administrator Teacher Single inheritance Derived class ( 或 subclass) AdministratorTeacher Multiple inheritance 4 2

Inheritance Examples 3 Shape TwoDimensionalShape ThreeDimensionalShape Circle Square Triangle Sphere Cube Tetrahedron 5 Inheritance: is-a relationship is-a Inheritance A derived class object can be treated as a base class object Examples a faculty is an employee a circle is a shape a car is a vehicle Never use inheritance, if the derived object is not a base object. 6 3

UML Example (C++): Inheritance X Shape UML: Class UML: Inheritance Y Circle class X { class Y : public X { 7 Objects and Pointers B D B bo, *bp; D do, *dp; D Instance Pointer Instance (do) Pointer (dp) Size depends on the class D Size is fixed (e.g., 32 bits) dp 8 4

Casting Inherited Objects and Pointers Up Down B D B bo, *bp; D do, *dp; Upcasting Downcasting Object Allowed safe bo = do; do = bo Not allowed Pointer Allowed safe bp = dp; Casting allowed dp = (D *) bp; (Next Page) Not safe or C++ static_cast 9 Use operator= to enable upcasting Upcasting/Downcasting Objects base class object derived class object class B { class D : public B { int b; int d; B bo; D do; bo = do; bo // ok derived class object base class object do = bo; // error do = (D) bo; // error do = static_cast<d> (bo); // error b memory model do b d Use operator= to enable downcasting 10 5

Upcasting Pointers pointer to base class object pointer to derived class object class B { class D : public B { void bf(); void df(); b B int b; int d; do d D B *bp; D do,*dp=&do; bp bp = dp; // ok: upcast dp bp = &do; // ok: upcast bp->bf(); // ok bp->df(); // error 11 Downcasting Pointers pointer to derived class object pointer to base class object class B { class D : public B { void bf(); void df(); int b; int d; b B do d D B bo,*bp; D do, *dp; bp = &do; // ok: upcast bp dp = bp; // error bp dp = (D *) bp; // ok: downcast dp->bf(); // ok dp = (D *) &bo; // legal: but, buggy 12 6

Introduction to polymorphism How do you attack an enemy? (next page) Select a number of soldiers Right click the enemy WC1 WC2 Introduction to polymorphism Select a number of soldiers We need a list that can store objects of different types (swordman, archery, cavalry, ) discussed later Soldier Swordsman Archery Cavalry 7

投影片 14 WC1 Woei-Kae Chen, 2014/9/22 WC2 Woei-Kae Chen, 2014/9/22

WC1 WC2 Introduction to polymorphism Right click the enemy We need to request different objects (swordman, archery, ) to do the same thing (attack the enemy) in different ways (using different weapons) What s wrong? // Attack the enemy for each soldier s in list { if (s.type == SWORDMAN) s.attack_with_sword(); else if (s.type == ARCHERY) s.attack_with_arrow(); Introduction to polymorphism 亞拉岡 16 8

投影片 15 WC1 Woei-Kae Chen, 2014/9/22 WC2 Woei-Kae Chen, 2014/9/22

Introduction to polymorphism 殺 17 Introduction to polymorphism 半獸人 18 9

Introduction to polymorphism 亞拉岡 半獸人 19 Introduction to polymorphism 士兵. 揮劍弓箭手. 射箭 20 10

Introduction to polymorphism // Attack the enemy for each soldier s in list { if (s.type == SWORDMAN) s.attack_with_sword(); else if (s.type == ARCHERY) s.attack_with_arrow(); // 將軍的 code for each soldier s in list { s. 攻擊 (); // 將軍的 code for each soldier s in list { if (s 是士兵 ) s. 揮劍 (); else if (s 是弓箭手 ) s. 射箭 (); else if (s 是大砲 ) s. 發射 (); Not a good design: 1. The soldiers should be smart 2. The General has too many responsibilities 3. When a new kind of soldiers is created, the general s code must be modified Introduction to polymorphism Another example How do you enlarge a number of graphical objects (in Powerpoint)? 22 11

Introduction to polymorphism Processing a list of unknown shapes 23 Declaring a list of unknown shapes Shape s[100]; // Bad Circle s[100]; // Bad Triangle s[100]; // Bad Shape *s[100]; // OK, 但怎麼呼叫? Solution: 設成 virtual function Shape 1. 混合 type 的 shape 怎麼儲存在 array? 2. 怎麼呼叫? s[0] = new Circle(); s[1] = new Triangle(); for (i=0;i<100;i++) s[i]->;//??? Circle Rectangle Triangle Does NOT work 24 12

Effect of Virtual Functions Example (non-virtual) class X { public: void f() { cout << x ; class Y : public X { public: void f() {cout<< y ; X a; a.f(); // x Y b; b.f(); // y X *p=&a; p->f(); X *p=&b; p->f(); // x // x Example (virtual) class X { public: virtual void f(){ cout << x ; class Y : public X { public: void f() {cout<< y ; X a; a.f(); // x Y b; b.f(); // y X *p=&a; p->f(); X *p=&b; p->f(); // x // y virtual 只對 pointer 或 reference 有效 (dynamic binding) 25 Virtual Functions for the shape problem 設成 virtual function Shape Java? Circle Rectangle Triangle Shape *s; s = new Circle(); s->; // 呼叫 circle 的 s = new Triangle(); s->; // 呼叫 Triangle 的 Shape *s[100]; // 設定 s[0..99] 分別指向哪一種物件 for (int i=0;i<100;i++) s[i]->; // 依據實際的 type 呼叫 26 13

Virtual Functions & Polymorphism Polymorphism Ability for objects of different classes to respond differently to the same function call Implemented through virtual functions C++ 允許使用 base class pointer( 或 reference) 呼叫 derived class 的 member function C++ chooses the correct overridden function in object Dynamic binding Function determined during execution time ShapePtr->Draw(); Static binding 已知 derivedobject Function determined during compile-time ShapeObject.Draw(); Pointer 可能指向任何 derivedobject 27 Dynamic Binding Static Binding Dynamic binding (run-time) 用 base class 的 pointer 或 reference 呼叫 virtual function Static binding (compile time) 其他 ( 用 object 呼叫 virtual/non-virtual function, 用 pointer 或 reference 呼叫 non-virtual function class X { public: void f1() { cout << xf1 ; virtual void f2() { cout << xf2 ; class Y : public X { public: void f1(){cout<< yf1 ; void f2(){cout<< yf2 ; X a; a.f1(); // xf1 static a.f2(); // xf2 static Y b; b.f1(); // yf1 static b.f2(); // yf2 static X *p=&a; p->f1(); // xf1 static p->f2(); // xf2 dynamic X *pb=&b; pb->f1(); // xf1 static pb->f2(); // yf2 dynamic 28 14

Abstract and Concrete Classes Abstract classes To provide a base class for other classes No objects can be instantiated Declare one or more pure virtual functions Example virtual void = 0; Concrete classes Objects can be instantiated No unimplemented virtual functions Implement all unimplemented virtual functions 29 Abstract and Concrete Classes C++ example class Shape { public: virtual void = 0; void setcolor(int c) { color = c; private: int color; virtual is inherited Abstract class Concrete class class Rectangle : public Shape { public: void { void getarea() { virtual void f() { Shape setcolor() Rectangle Not pure virtual 30 15

Abstract and Concrete Classes UML example 斜體字 pure virtual function 正體字有 implementation Shape setcolor() 斜體字 abstract class 正體字 concrete class Circle Rectangle Triangle 31 Virtual Destructors Problem: How to delete an object with a base class pointer? Example: 32 16

Solution: Virtual Destructors declare a virtual (base-class) destructor class X { public: virtual ~X(); // virtual destructor private: class Y : public X { X *pa = new Y; // use *pa delete pa; 33 WC1 WC2 Introduction to polymorphism Which code runs faster? // 將軍的 code for each soldier s in list { if (s.type == SWORDMAN) s.attack_with_sword(); else if (s.type == ARCHERY) s.attack_with_arrow(); Switch? // 將軍的 code for each soldier s in list { s. 攻擊 (); 17

投影片 34 WC1 Woei-Kae Chen, 2014/9/22 WC2 Woei-Kae Chen, 2014/9/22

How does compiler handle virtual functions? virtual functions Overheads? memory speed How it works? dynamic binding vtable Abstract class Shape Point Circle Cylinder 35 vtable virtual functions functions 每個 class 都有一個 vtable 每個 object 都帶著 vtable 的 pointer array Memory overhead? Speed overhead? bp->psn(); 36 18