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

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
V IRTUAL F UNCTIONS Chapter 10 Department of CSE, BUET 1.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Inheritance, Polymorphism, and Virtual Functions
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism &Virtual Functions
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism and Virtual Functions. Topics Polymorphism Virtual Functions Pure Virtual Functions Abstract Base Classes Virtual Destructors V-Tables Run.
Chapter 10 Inheritance and Polymorphism
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Chapter 9 Questions 1. What are the difference between constructors and member functions? 2. Design and implement a simple class as you want, with constructors.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Final Review Spring, Overall Assessment –Lecture Course  Continuous assessment 40% Attendance 10% Homework questions 10% Course projects 20% 
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Abstract Classes Course Lecture Slides 7 June 2010 “None of the abstract.
1 Chapter 4 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 11 Inheritance and Polymorphism.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
1 Chapter 2 Inheritance and Polymorphism. 2 Objectives u To develop a subclass from a superclass through inheritance. u To invoke the superclass’s constructors.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 10 Inheritance and Polymorphism.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
A First Book of C++ Chapter 12 Extending Your Classes.
Chapter 2 Objects and Classes
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Chapter 15 Abstract Classes and Interfaces
Chapter 11 Inheritance and Polymorphism
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Andy Wang Object Oriented Programming in C++ COP 3330
Polymorphism & Virtual Functions
Polymorphism Lec
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 9 Inheritance and Polymorphism
Learning Objectives Inheritance Virtual Function.
Virtual Functions Department of CSE, BUET Chapter 10.
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Today’s Objectives 10-Jul-2006 Announcements Quiz #3
Chapter 14 Abstract Classes and Interfaces
Chapter 11 Inheritance and Polymorphism
Computer Science II for Majors
Presentation transcript:

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 §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 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 Example of Inheritance GeometricObject.h GeometricObject.cpp DerivedCircle.h DerivedCircle.cpp Rectangle.h Rectangle.cpp TestGeometricObject Run

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 §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 Summary of Accessibility Keyword Keyword In Class Itself In Derived Class In Others public √√√ protected √√ ╳ private √ ╳ ╳

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

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 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 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 §11.4 Multiple Inheritance  Type of Inheritance Single ( 单重 ) Multiple( 多重 ) Repeated( 重复 ) D B A C BC A D BC A

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 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 §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 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 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 §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 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 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 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 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 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 §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 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 Abstract Class Example AbstractGeometricObject.h Run AbstractGeometricObject.cpp DerivedCircle2.h DerivedCircle2.cpp Rectangle2.h Rectangle2.cpp TestGeometricObject2.cpp

27 §11.8 Dynamic Casting  The display function in Listing :  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 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 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 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 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 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 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 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?