Docsity

Understanding Polymorphism & Virtual Functions in C++: Base Pointers & Dynamic Binding, Slides of Programming for Engineers

Partial preview of the text

Download Understanding Polymorphism & Virtual Functions in C++: Base Pointers & Dynamic Binding and more Slides Programming for Engineers in PDF only on Docsity!

Virtual Functions and

Polymorphism

Chapter-

Interesting Fact

  • Pointer of a base class can hold addresses of objects of its derived classes
  • Consider Point and Circle classes of previous lecture

class Point {

//implementation };

class Circle:public Point {

//implementation };

void main(void){

Point *p = new Circle(3,3,2.5);

}

Above code is correct. Is there any problem?

YES: If we call Display function through p then which function will execute

Polymorphism

  • Execution of different functions by sending same message
  • Polymorphism is a concept where a single name may denote objects of different classes that are related by some common base class.
  • In polymorphic languages some values and variables may have more than one type
  • A function is polymorphic if it may be applied to arguments of different types

Type Fields and switch statements

  • We can make type field in class to identify type of its instance, when instance’s address is stored in a base class pointer variable
  • And then can use switch statements to test the type of object and call appropriate functions explicitly
  • More error prone and less efficient
  • Better solution is use of Virtual Functions

Example of Shape Class

  • Consider hierarchy of shape class
  • Shape
    • Two dimensional shape
      • Rectangle, square, Circle etc.
    • Three dimensional shape
      • Cube, parallelogram, sphere etc.
  • We want to use same message for drawing all objects, even when they are stored in base class pointer variable
  • Declare Draw method as virtual in Shape class, and override it in child classes

Abstract base classes and Concrete

Classes

  • Class is a type, and it is assumed that objects of this type will be created
  • But actually creating instance of all classes is not required
  • Classes for which programmer never intends to create an object , are called abstract classes ( abstract base classes )
  • Objects of abstract base classes can not be created
  • Classes from which objects can be instantiated are called concrete classes

Derived-Class Member-Function Calls via Base-

Class Pointers

  • Handle (pointer/reference)
    • Base-pointer can aim at derived-object
      • But can only call base-class functions
    • Calling derived-class functions is a compiler error
      • Functions not defined in base-class
  • Common theme
    • Data type of pointer/reference determines functions it can call

Abstract Classes

  • Abstract classes not required, but helpful
  • To make a class abstract
    • Need one or more "pure" virtual functions
      • Declare function with initializer of 0 virtual void draw() const = 0;
    • Regular virtual functions
      • Have implementations, overriding is optional
    • Pure virtual functions
      • No implementation, must be overridden
    • Abstract classes can have data and concrete functions
      • Required to have one or more pure virtual functions

Case Study: Payroll System Using

Polymorphism

  • Create a payroll program
    • Use virtual functions and polymorphism
  • Problem statement
    • 4 types of employees, paid weekly
      • Salaried (fixed salary, no matter the hours)
      • Hourly workers
      • Commission (paid percentage of sales)
      • Base-plus-commission (base salary + percentage of sales)

Case Study: Payroll System Using

Polymorphism

  • Base class Employee
    • Pure virtual function earnings (returns pay)
      • Pure virtual because need to know employee type
      • Cannot calculate for generic employee
    • Other classes derive from Employee Employee

SalariedEmployee CommissionEmployee HourlyEmployee

BasePlusCommissionEmployee

Employee::Employee(const char *first, const char *last) { firstName = new char[ strlen(first) + 1 ]; strcpy(firstName, first); lastName = new char[ strlen(last) + 1 ]; strcpy(lastName, last); } // Destructor deallocates dynamically allocated memory Employee::~Employee() { delete [] firstName; delete [] lastName; } // Return a pointer to the first name char *Employee::getFirstName() const { return firstName; // caller must delete memory } char *Employee::getLastName() const { return lastName; // caller must delete memory }

class SalariedEmployee: public

Employee {

public:

SalariedEmployee(const char *,

const char *,

float = 0.0);

void setWeeklySalary(float);

virtual float earnings() const;

virtual void print() const;

private:

float weeklySalary;

class CommissionWorker : public

Employee {

public:

CommissionWorker(const char *, const

char *, float = 0.0, unsigned = 0);

void setCommission(float);

void setQuantity(unsigned);

virtual float earnings() const;

virtual void print() const;

private:

float commission; // amount per item

sold

unsigned quantity; // total items sold

for week

CommissionWorker::CommissionWorker(const char *first, const char *last, float c, unsigned q) : Employee(first, last) // call base-class constructor { commission = c > 0? c : 0; quantity = q > 0? q : 0; } void CommissionWorker::setCommission(float c) { commission = c > 0? c : 0; } void CommissionWorker::setQuantity(unsigned q) { quantity = q > 0? q : 0; } float CommissionWorker::earnings() const { return commission * quantity; } void CommissionWorker::print() const { cout << endl << "Commission worker: " << getFirstName() << ' ' << getLastName(); } docsity.com