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