Docsity

C++ Polymorphism: Abstract Base Classes & Virtual Functions, Slides of Computer Science

Partial preview of the text

Download C++ Polymorphism: Abstract Base Classes & Virtual Functions and more Slides Computer Science in PDF only on Docsity!

Chapter 20 - Virtual Functions

Outline 20.1 Introduction 20.2 Type Fields and switch Statements 20.3 Virtual Functions 20.4 Abstract Base Classes and Concrete Classes

20.1 Introduction

  • virtual functions and polymorphism
    • Design and implement systems that are more easily

extensible

  • Programs written to generically process objects of all

existing classes in a hierarchy

20.3 Virtual Functions

  • virtual functions
    • Used instead of switch statements
    • Declaration:
      • Keyword virtual before function prototype in base class virtual void draw() const;
    • A base-class pointer to a derived class object will call the correct draw function
    • If a derived class does not define a virtual function it is inherited from the base class

20.3 Virtual Functions (II)

  • ShapePtr->Draw();
    • Compiler implements dynamic binding
    • Function determined during execution time
  • ShapeObject.Draw();
    • Compiler implements static binding
    • Function determined during compile-time

20.4 Abstract and Concrete Classes (II)

  • Making abstract classes
    • Declare one or more virtual functions as “pure” by

initializing the function to zero

virtual double earnings() const = 0;

  • Pure virtual function