Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 11 Inheritance and Polymorphism §11.1 Concept of Inheritance §11.2 Accessibility in Inheritance §11.3 Constructor/Destructor in Inheritance §11.4.

Similar presentations


Presentation on theme: "Chapter 11 Inheritance and Polymorphism §11.1 Concept of Inheritance §11.2 Accessibility in Inheritance §11.3 Constructor/Destructor in Inheritance §11.4."— Presentation transcript:

1 Chapter 11 Inheritance and Polymorphism §11.1 Concept of Inheritance §11.2 Accessibility in Inheritance §11.3 Constructor/Destructor in Inheritance §11.4 Multiple Inheritance §11.5 Redefining Functions §11.6 Virtual Function and Polymorphism §11.7 Abstract Classes §11.8 Dynamic Casting

2 2 §11.1 Concept of Inheritance ( 继承 )  The “is a” relationship Apple is a fruit Elephant is an animal Circle is a shape  A is a B  A has the characteristics/features/properties of B  A inherits B  Class A inherits class B Inheritance can extend existing classes!

3 3 Class Inheritance  Syntax: B A 基类 父类 超类 Base Parent Super-Class 派生类 子类 Derived-Class Child class DerivedClass : acckeyword BaseClass{…}; class A: public B{ public: … private: … }; B A

4 4 Example of Inheritance GeometricObject.h GeometricObject.cpp DerivedCircle.h DerivedCircle.cpp Rectangle.h Rectangle.cpp TestGeometricObject Run

5 5 A Tip about Generic Programming( 泛型编程 )  With inheritance, an object of a derived class can be used wherever an object of the base class is required This is a kind of GP  GP permits writing common functions or types that differ only in the types operated onfunctionstypes Template ( 模板 ) (in Chapter 15) is the main GP technique in C++ void showArea(GeometricObject gb){…}; Circle cl; Rectangle rt; showArea( cl); showArea(rt);

6 6 §11.2 Accessibility in Inheritance  The protected Keyword A protected data field or function can be accessed by name in its derived classes class B { public: int i; protected: int j; private: int k; }; class A: public B{ public: void display(){ cout << i << endl; cout << j << endl; cout << k << endl; } }; int main(){ A a; cout << a.i << endl; cout << a.j << endl; cout << a.k << endl; a.display(); return 0; }

7 7 Summary of Accessibility Keyword Keyword In Class Itself In Derived Class In Others public √√√ protected √√ ╳ private √ ╳ ╳

8 8 Accessibility after Inheritance Accessibility in BaseInheritanceAccessibility in Derived public protected private ╳ public protected private ╳ public private protectedprivate ╳ The stricter is adopted!

9 9 §11.3 Constructor/Destructor in Inheritance  The constructors of a base class are not inherited  How to initialize the data fields inherited from the base class?  By calling base class constructors from the constructors of the derived classes A ( Except constructors ) B

10 10 Calling Base Class Constructors DerivedClass(parameterList): BaseClass() { // Perform initialization } DerivedClass(parameterList): BaseClass(argumentList) { // Perform initialization } Circle::Circle(double radius, string color, bool filled) :GeometricObject(color, filled) { this->radius = radius; } Ever saw before? Constructor Initializer! class Action{ public: Action(int hr, int min, int sec) :time(hr, min, sec) { } private: Time time; }; Object name! Class name!

11 11 No-Arg Constructor in Base Class A constructor in a derived class must always invoke a constructor in its base class. If a base constructor is not invoked explicitly, the base class’s no-arg constructor is invoked by default. For example,

12 12 §11.4 Multiple Inheritance  Type of Inheritance Single ( 单重 ) Multiple( 多重 ) Repeated( 重复 ) D B A C BC A D BC A

13 13 Multiple Inheritance  Syntax:  For example: class DerivedClass : acckeyword BaseClass, acckeyword BaseClass { … }; class CPolygon { … }; class COutput { … }; class CRectangle :public CPolygon, public COutput { public: int area () { return (width * height); } };

14 14 Constructor and Destructor Chaining  More than one constructor/destructor to invoke A() ~A() C() ~C() ME() ~ME() class A: public B{... }; class ME: public A, public C{... D d; }; B() ~B() D() ~D() Invoking order of constructors: B, A, C, D, ME Invoking order of destructors: in reverse order ChainingDemo Run

15 15 §11.5 Redefining Functions  A function of the base class may be redefined( 重 新定义) in the derived class  For example: string GeometricObject::toString() { return "Geometric object color " + color + " filled " + ((filled) ? "true" : "false"); } string Circle::toString() { return "Geometric object color " + color + " filled " + ((filled) ? "true" : "false“+ “radius “+ radius); }

16 16 Redefining vs. Overloading Overloading( 重载 )Redefining( 重定义 ) Similarity  More than one function  The same name Difference  Different signature (parameter list)  Maybe different type (return type)  The same signature  The same type  To provide various choices  To shield/hide the original function

17 17 Invoking Functions Redefined  To invoke the function defined in the derived class: circle1.toString();  To invoke the function defined in the base class: circle1.GeometricObject::toString(); Scope resolution operator ( 作用域解析运算符 )

18 18 §11.6 Virtual Function and Polymorphism  What we want? class HM { public: void show(){ cout<<"Human\n"; } }; class CN: public HM { public: void show(){ cout<<“Chinese\n"; } }; class CT: public CN{ public: void show(){ cout<<“Cantonese\n"; } }; int main(){ HM * hm = new HM(); hm->show(); delete hm; hm = new CN(); hm->show(); delete hm; hm = new CT(); hm->show(); delete hm; } Human Chinese Cantonese Polymorphism ( 多态 )

19 19 Polymorphism  Listing 11.9 to demonstrate polymorphism  Polymorphism( 多态 ) Also called dynamic binding ( 动态绑定 )  Two elements Virtual function ( 虚函数 ) Pointer of base class Run WhyPolymorphismDemo Run PolymorphismDemo

20 20 Virtual Functions  The function declared with the keyword “virtual”  Overriding To redefine a virtual function in the derived class class C { public: virtual string toString() { return "class C"; } }; class B: public C { string toString() { return "class B"; } };

21 21 Note  If a function is defined virtual in a base class, it is automatically virtual in all its derived classes  It is not necessary to add the keyword virtual in the function declaration in the derived class

22 22 Pointer of Base Class void displayObject(C *p) { cout toString().data() << endl; } int main() { A a = A(); B b = B(); C c = C(); displayObject(&a); displayObject(&b); displayObject(&c); return 0; } Class A Class B Class C

23 23 Matching vs. Binding  Matching ( 匹配 ) To match the function call with the function signature At compiling time  Binding ( 绑定 ) To bind the function call with the function implementation Two types of binding  Static binding( 静态绑定,early binding) At compiling time  Dynamic binding( 动态绑定, late binding)  polymorphism At runtime

24 24 §11.7 Abstract Classes  Class is the abstraction of instances/objects  A base class is more abstract/general than derived classes  Abstract class ( 抽象类 ) In logic:  A class so abstract that it cannot have any specific instances  It can only be used as base class In syntax:  A class with abstract functions ( 抽象函数 ) For example, GeometricObjectGeometricObject

25 25 Abstract Function  I.e. Pure Virtual Function ( 纯虚函数 ) Can ’ t be implemented in abstract classes  For example class GeometricObject{ protected: GeometricObject(); GeometricObject(string color, bool filled); public: string getColor(); void setColor(string color); bool isFilled(); void setFilled(bool filled); string toString(); virtual double getArea() = 0; virtual double getPerimeter() = 0; private: string color; bool filled; };

26 26 Abstract Class Example AbstractGeometricObject.h Run AbstractGeometricObject.cpp DerivedCircle2.h DerivedCircle2.cpp Rectangle2.h Rectangle2.cpp TestGeometricObject2.cpp

27 27 §11.8 Dynamic Casting  The display function in Listing 11.18 :  How to display radius, diameter, area, and perimeter if the object is a circle? // A function for displaying a geometric object void displayGeometricObject(GeometricObject &object) { cout << "The area is " << object.getArea() << endl; cout << "The perimeter is " << object.getPerimeter() << endl; }

28 28 Dynamic Casting  The dynamic_cast operator checks if p points to a Circle object If yes, p1 is assigned the address of the object If no, p1 is assigned to NULL (the constant 0) GeometricObject *p = &object; Circle *p1 = dynamic_cast (p); if (p1 != NULL) { cout getRadius() << endl; cout getDiameter() << endl; } Run DynamicCastingDemo

29 29 Upcasting and Downcasting  Upcasting Assigning a pointer of a derived class type to a pointer of its base class type Done implicitly  Downcasting Assigning a pointer of a base class type to a pointer of its derived class type Done explicitly using dynamic_cast GeometricObject *p = new Circle(1); Circle *p1 = new Circle(2); p = p1; p1 = dynamic_cast (p);

30 30 The typeid Operator  To return the type information of a variable/object The information is stored in an object of class type_info  For example, string x; cout << typeid(x).name() << endl;

31 31 A Summary  Concept of inheritance  The protected keyword  Accessibility in derived calsses  Multiple Inheritance, constructor/destructor chaining  Virtual function and polymorphism  Pure virtual functions and abstract classes  The dynamic_cast operator

32 32 Homework Questions 1.Point out the errors in the following code. Assume the implementation of the classes is correct and omitted due to the limit of space. class BOX{ public: BOX(int, int, int, int, char*, int); ~BOX(); int show(); int hide(); int move(int, int); int zoom(int); protected: int draw(); int start_x, start_y; int width, height; char *title; int color; }; class DialogBox: BOX{ public: DialogBox(int, int, int, int, char*, int, char*, char*); ~DialogBox(); int select(); private: int draw(); char *ok_button; char *cancel_button; }; //…. The Implementation of the classes is omitted.// int main(){ DialogBox dlg(0, 0, 15, 13, "test", 1, "OK", "Cancel"); dlg.move(19, 20); }

33 33 Homework Questions (con’t) 2.Write down the output of the following code. class Base1{ public: Base1( int x ){ cout<<"Const. Base1.\n"; value = x; } int getData(){ return value; } protected: int value; }; class Derived :public Base2, public Base1{ public: Derived( int i, char ch, double db ) : Base1( i ), Base2( ch ), real( db ) { cout<<"Const. Derived.\n"; } double getReal(){ return real; } private: double real; }; int main() { Base1 base1( 10 ); Base2 base2( 'Z' ); Derived derived( 7, 'A', 3.5 ); return 0; } class Base2{ public: Base2( char ch ){ cout<<"Const. Base2.\n"; letter = ch; } char getData() const{ return letter; } protected: char letter; };

34 34 Homework Questions (con’t) 3.Describe the difference between “virtual function” and “abstract function”. 4.How is the polymorphism enabled? 5.What is the difference between dynamic casting and static casting?


Download ppt "Chapter 11 Inheritance and Polymorphism §11.1 Concept of Inheritance §11.2 Accessibility in Inheritance §11.3 Constructor/Destructor in Inheritance §11.4."

Similar presentations


Ads by Google