Lecture11-Polymorphism_II

Lecture11-Polymorphism_II - Computer Programming II Lecture...

Info iconThis preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Computer Programming II Lecture 11 Dynamic polymorphism and abstract classes 1 To enable dynamic polymorphism via virtual function To understand the benefit of dynamic polymorphism To understand why virtual destructor is needed To understand abstract base class To declare an abstract class via pure virtual function Good programming practices Learning Objectives 2 Introduction l Recall that binding is a process of connecting a function call to a function body . l Early/Static/Compile-time binding is the binding that is performed before the program is run or during compilation . l Late/Dynamic/Runtime binding is the binding that is performed at run-time . l A method is dynamic-polymorphic if its binding occurs at run time rather than compile time. 3 Animal + move() Bird + move() Recall the Animal hierarchy, if subclass Bird does override superclass Animal move() method Static Polymorphism: Problem class Animal { public: void move() { cout << "Moving"; } }; class Bird : public Animal { public: void move() { cout << "Flying"; } }; 4 Call the move() method for a Bird object using a pointer/reference to/of an Animal object ( upcasting ) Got overriding and got upcasting => got problem int main() { Bird* b1 = new Bird; Animal * a1 = b1; // Upcasting via pointer a1->move(); // cout "Moving " Bird b2; a1 = &b2; // Upcasting via pointer a1->move(); // cout "Moving " Animal & a2 = b2; // Upcasting via reference a2. move(); // cout "Moving " delete b1; } Animal::move() is still called but Bird::move() is more appropriate/precise/accurate in the context. This happens when upcasting Static Polymorphism: Problem 5 Virtual Function class Animal { public: virtual void move() { // enable dynamic binding cout << "Moving"; } }; class Bird : public Animal { public: void move() { // automatically virtual cout << "Flying"; } }; In order to allow a method...
View Full Document

This note was uploaded on 02/03/2012 for the course IT 1241 taught by Professor Pang during the Spring '11 term at Multimedia University, Cyberjaya.

Page1 / 19

Lecture11-Polymorphism_II - Computer Programming II Lecture...

This preview shows document pages 1 - 7. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online