720 likes | 731 Views
This article provides an overview of polymorphism in object-oriented programming, discussing concepts such as inheritance, over-riding, and virtual functions. It explores the benefits of using polymorphism in software development and demonstrates how it can be implemented using class hierarchies.
E N D
Summary: Derived Class • ‘is-a’ relationship • Different from ‘has-a’ or ‘uses-a’, or … by class-in-class • Public inheritance • Public • Private • ‘protected’ • Constructors/destructors • Redefinition (over-riding) … polymorphism …
Over-riding (not over-loading): Reusing Operations of Base Classes class X { f(); }; Class Y : public X {}; void Y::f() { … X::f(); … } X x; Y y; x.f(); y.f(); Derived class may extend or replace base class function of the same name (homonym, homonymous) • Therefore, it hides (or overrides) the base-class version of the function • Still possible to call the base class function with scope resolution operator
class Employee { double pay(); … } class Manager : public Employee { double pay(); } double Employee::pay() { return 10000; } double Manager::pay() { return 10*Employee::pay(); } int main () { Employee e; Manager m; cout << e.pay(); cout << m.pay(); }
What is Polymorphism? • Polymorphism: poly + morph • (biology): the existence of two or more forms of individuals within the same animal species • In programming languages • implementation of ‘inheritance’ • Objects belonging to different types (classes) call methods of the same name, but of different behavior. • ‘over-loading’ is one type of polymorphism: static binding • Same names, but different arguments • ‘over-riding’ is another type, static binding • Same names, but different classes • ‘virtual function’ is a new type: dynamic binding • Same names, but different ‘classes’ with the same hierarchy
Polymorphism with inheritance hierarchies • Treat objects of classes that are part of the same hierarchy as if they are objects of a single class • E.g., vehicles 4-wheel vehicle passenger car sport car • Objects can be created in any part of the chain of hierarchy • Each object performs the correct tasks for that object’s type • Different actions occur depending on the type of object • New classes can be added with little or no modification to existing code
Practical Motivation • the pointers/references are logically ‘compatible’ for the base and derived classes • with ‘static typing or binding’, at compilation, it can only be fixed based on the ‘type/class’ of the pointers/references, but not the actual objects (base or derived class) • the ‘resolution’ should be delayed to the ‘run-time’, so to introduce ‘dynamic binding’ • ‘virtual function’ explicitly enforces ‘dynamic binding’
Pointers, Dynamic Objects, and Classes class Employee { double pay(); … } class Manager : public Employee { double pay(); } int main() { Employee* ep; ep = new Employee; // OK … ep = new Manager; // OK … Manager* mp; mp = new Manager; // OK … mp = new Employee; // error! } A ‘manager’ is an ‘employee’, so an employee pointer (base class pointer) can point to a manager object (derived class object). But, an ‘employee’ is not necessarily a ‘manager’, so a manager pointer (derived class pointer) CANNOT point to an employee object (base class object)!
Good Pointers, but Wrong Functions! class Employee { double pay(); … } class Manager : public Employee { double pay(); } int main() { Employee* ep; ep = new Employee; … ep = new Manager; … ep->pay()? // always Employee::pay(), // never Manager::pay()!!! Whose pay?
‘Virtual’ is polymorphic class Employee { virtual double pay(); … } class Manager : public Employee { double pay(); } Employee* ep; ep = new Employee; … ep = new Manager; … ep->pay(); // always the right one, // either Employee::pay(), or Manager::pay()!!!
(non-virtual) Static and (virtual) Dynamic Binding • The compiler determines which version of the function or class to use during the compilation time for • Function overloading • Function and class template substantiations • Which version is called must be deferred to run time • This is dynamic binding
‘Virtual’ is polymorphic class Employee { virtual double pay(); … } class Manager : public Employee { double pay(); void meetings();??? } Employee* ep; ep = new Employee; … ep = new Manager; … ep->pay(); // always the right one, // either Employee::pay(), or Manager::pay()!!!
Invoking functions with pointers/references • Cannot aim derived-class pointer to a base-class object • Aim base-class pointer at base-class object • Invoke base-class functionality • Aim derived-class pointer at derived-class object • Invoke derived-class functionality • Aim base-class pointer at derived-class object • Because derived-class object is an (inherited) object of base class • Can only invoke base-class functionalities • Invoked functionality depends on the pointer/reference type used to invoke the function (which is base or derived object). • Therefore, if it is base pointer, even if it points to a derived-class object, it invokes the functionality of base class CommissionEmployee1.h, CommissionEmployee1.cpp, BasePlusCommissionEmployee1.h, BasePlusCommissionEmployee1.cpp, test1a.cpp
CommissionEmployee1.h class CommissionEmployee { public: CommissionEmployee( const string &, const string &, const string &, double = 0.0, double = 0.0 ); void setFirstName( const string & ); // set first name string getFirstName() const; // return first name ... double earnings() const; // calculate earnings void print() const; // print CommissionEmployee object Function earnings and print will be redefined in derived classes to calculate the employee’s earnings Function print will be redefined in derived class to print the employee’s information
BasePlusCommissionEmployee1.h class BasePlusCommissionEmployee : public CommissionEmployee { public: BasePlusCommissionEmployee( const string &, const string &, const string &, double = 0.0, double = 0.0, double = 0.0 ); void setBaseSalary( double ); // set base salary double getBaseSalary() const; // return base salary double earnings() const; // calculate earnings void print() const; // print BasePlusCommissionEmployee object private: double baseSalary; // base salary }; // end class BasePlusCommissionEmployee Redefine functions earnings and print
Test1a.cpp sample output (1/2) Print base-class and derived-class objects: commission employee: Sue Jones social security number: 222-22-2222 gross sales: 10000.00 commission rate: 0.06 base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: 5000.00 commission rate: 0.04 base salary: 300.00 Calling print with base-class pointer to base-class object invokes base-class print function: commission employee: Sue Jones social security number: 222-22-2222 gross sales: 10000.00 commission rate: 0.06
Test1a.cpp sample output (2/2) Calling print with derived-class pointer to derived-class object invokes derived-class print function: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: 5000.00 commission rate: 0.04 base salary: 300.00 Calling print with base-class pointer to derived-class object invokes base-class print function on that derived-class object: commission employee: Bob Lewis social security number: 333-33-3333 gross sales: 5000.00 commission rate: 0.04
The pointer must be a base-class pointer, pointing to a derived-class object • All the base class functions of the derived object can be called. This is not a problem because derived class inherits all the functions from the base class. • Because it is a base class pointer, cannot access the members of derived-class even if the base-class pointer is pointing to the derived-class object • Aim a derived-class pointer at a base-class object is an error • C++ compiler generates error • CommissionEmployee (base-class object) is not a BasePlusCommissionEmployee (derived-class object) • This is because • A derived-class pointer is supposed to be able to access all the derived-class member functions that it points to • If the pointer is pointing to a base class, some of these derived-class functions may not even be available at the base class
Test1b.cpp CommissionEmployee commissionEmployee( "Sue", "Jones", "222-22-2222", 10000, .06 ); BasePlusCommissionEmployee *basePlusCommissionEmployeePtr = 0; // aim derived-class pointer at base-class object // Error: a CommissionEmployee is not a BasePlusCommissionEmployee basePlusCommissionEmployeePtr = &commissionEmployee; Cannot assign base-class object to derived-class pointer
// aim base-class pointer at derived-class object commissionEmployeePtr = &basePlusCommissionEmployee; // invoke base-class member functions on derived-class // object through base-class pointer (allowed) string firstName = commissionEmployeePtr->getFirstName(); tester1c: Aiming base-class pointer at derived-class object • Calling functions that exist in base class causes base-class functionality to be invoked • Calling functions that do not exist in base class (may exist in derived class) will result in error • Derived-class members cannot be accessed from base-class pointers
CommissionEmployee2.h class CommissionEmployee { public: CommissionEmployee( const string &, const string &, const string &, double = 0.0, double = 0.0 ); void setFirstName( const string & ); // set first name string getFirstName() const; // return first name ... virtual double earnings() const; // calculate earnings virtual void print() const; // print CommissionEmployee object • Declaring earnings and print as virtual allows them to be overridden • Overridden means superceding the base class codes • Not redefined, meaning that the original function of the base class still exists
BasePlusCommissionEmployee2.h class BasePlusCommissionEmployee : public CommissionEmployee { public: BasePlusCommissionEmployee( const string &, const string &, const string &, double = 0.0, double = 0.0, double = 0.0 ); void setBaseSalary( double ); // set base salary double getBaseSalary() const; // return base salary virtual double earnings() const; // calculate earnings virtual void print() const; // print private: double baseSalary; // base salary }; // end class BasePlusCommissionEmployee Functions earnings and print are already virtual – good practice to declare virtual even with overriding function (though optional)
tester2.cpp (1/3) // output objects using static binding cout << "Invoking print function on base-class and derived-class " << "\nobjects with static binding\n\n"; commissionEmployee.print(); // static binding basePlusCommissionEmployee.print(); // static binding // output objects using dynamic binding cout << "\n\n\nInvoking print function on base-class and “ << "derived-class \nobjects with dynamic binding"; // aim base-class pointer at base-class object and print commissionEmployeePtr = &commissionEmployee; cout << "\n\nCalling virtual function print with base-class pointer" << "\nto base-class object invokes base-class " << "print function:\n\n"; commissionEmployeePtr->print(); // invokes base-class print Aiming base-class pointer at base-class object and invoking base-class functionality
tester2.cpp (2/3) // aim derived-class pointer at derived-class object and print basePlusCommissionEmployeePtr = &basePlusCommissionEmployee; cout << "\n\nCalling virtual function print with derived-class “ << "pointer\nto derived-class object invokes derived-class “ << "print function:\n\n"; basePlusCommissionEmployeePtr->print(); Aiming derived-class pointer at derived-class object and invoking derived-class functionality
tester2.cpp (3/3) // aim base-class pointer at derived-class object and print commissionEmployeePtr = &basePlusCommissionEmployee; cout << "\n\nCalling virtual function print with base-class pointer" << "\nto derived-class object invokes derived- class " << "print function:\n\n"; // polymorphism; invokes BasePlusCommissionEmployee's print; // base-class pointer to derived-class object commissionEmployeePtr->print(); Aiming base-class pointer at derived-class object and invoking derived-class functionality via polymorphism and virtual functions
tester2.cpp Sample Output (1/3) Invoking print function on base-class and derived-class objects with static binding commission employee: Sue Jones social security number: 222-22-2222 gross sales: 10000.00 commission rate: 0.06 base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: 5000.00 commission rate: 0.04 base salary: 300.00 Invoking print function on base-class and derived-class objects with dynamic binding
tester2.cpp Sample Output (2/3) Calling virtual function print with base-class pointer to base-class object invokes base-class print function: commission employee: Sue Jones social security number: 222-22-2222 gross sales: 10000.00 commission rate: 0.06 Calling virtual function print with derived-class pointer to derived-class object invokes derived-class print function: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: 5000.00 commission rate: 0.04 base salary: 300.00
tester2.cpp Sample Output (3/3) Calling virtual function print with base-class pointer to derived-class object invokes derived-class print function: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: 5000.00 commission rate: 0.04 base salary: 300.00
Abstract Classes ‘Employee’: both base class and derived class are useful objects ‘Shape’ represents an abstract concept for which objects cannot exist. ‘shape’ makes sense only as the base of some class derived from it. class Shape { void rotate(int); void draw(); … } class Circle : public Shape { … } Shape s; ??? class Employee { string firstName; string familyName; … } class Manager : public Employee { list<Employee*> group; … }
Virtual Functions A ‘virtual’ function in a base class will be redefined in each derived class class Shape { virtual void rotate(int); virtual void draw(); … } class Circle : public Shape { public: void rotate(int); void draw(); … private: int radius; }
‘Pure’ Virtual Functions A ‘virtual’ function is ‘made pure’ by the initializer = 0. class Shape { virtual void rotate(int) = 0; virtual void draw() = 0; … } class Circle : public Shape { public: void rotate(int); void draw(); … private: int radius; }
Abstract Class A class with one or more pure virtual functions is an ‘abstract’ class, And no objects of that abstract class can be created! An abstract class is only used as an interface and as a base for other classes. class Shape { virtual void rotate(int) = 0; virtual void draw() = 0; … } class Circle : public Shape { public: void rotate(int); void draw(); … private: int radius; } Shape s; // error!!! Circle c;
A pure virtual function that is not defined in a derived class remains a pure virtual function, so the derived class is still an abstract class. class Shape { virtual void rotate(int) = 0; virtual void draw() = 0; … } class Polygon : public Shape { public: bool is_closed() { return true; } } Polygon p; // error!!!
(non-virtual) Static and (virtual) Dynamic Binding • The compiler determines which version of the function or class to use during the compilation time for • Function overloading • Function and class template substantiations • Which version is called must be deferred to run time • This is dynamic binding
‘Virtual’ is polymorphic class Employee { virtual double pay(); … } class Manager : public Employee { double pay(); void meetings();??? } Employee* ep; ep = new Employee; … ep = new Manager; … ep->pay(); // always the right one, // either Employee::pay(), or Manager::pay()!!!
Abstract Class A class with one or more pure virtual functions is an ‘abstract’ class, And no objects of that abstract class can be created! An abstract class is only used as an interface and as a base for other classes. class Shape { virtual void rotate(int) = 0; virtual void draw() = 0; … } class Circle : public Shape { public: void rotate(int); void draw(); … private: int radius; } Shape s; // error!!! Circle c;
Pure Virtual Functions and Abstract Classes • We can use the abstract base class to declare pointers and references • Can point to objects of any concrete class derived from the abstract class • Programs typically use such pointers and references to manipulate derived-class objects polymorphically • Polymorphism is particularly effective for implementing software systems • Reading or writing data from and to different devices of the same base class • Example: Iterator class • Can traverse all the objects in a container 39
#include <iostream> using namespace std; class base{ public: virtual void print() = 0; virtual void print2() = 0; }; class derived1: public base{ public: virtual void print(){ cout << "derived1\n"; } virtual void print2(){} // must have this line, // otherwise compiler complains in main() }; class derived2: public base{ public: virtual void print(){ cout << "in derived2\n"; } // do not need to define print2() here as // derived2 is not a concrete class }; class derived3: public derived2{ public: virtual void print2(){ cout << "In derived3\n"; } }; int main(){ derived1 d1; // derived2 d2; compiler complains: // the following virtual functions are abstract: // void base::print2() derived3 d3; d1.print(); d3.print(); // can do that! d3.print2(); return 1; } derived1 in derived2 In derived3 40
Constructors cannot be virtual • Destructors can be virtual • Usually they should be virtual to have ‘polymorphic’ behavior
Virtual Destructors • Nonvirtual destructors • Destructors that are not declared with keyword virtual • If a derived-class object is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the behavior is undefined • This is because delete may be applied on a base-class object, instead of the derived class • virtual destructors • Declared with keyword virtual • That means that all derived-class destructors are virtual • With that, if a derived-class object is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the appropriate derived-class destructor is then called • Appropriate base-class destructor(s) will execute afterwards
#include <iostream> using namespace std; class Base{ public: virtual ~Base() { cout <<"Base Destroyed\n"; } }; class Derived: public Base{ public: virtual ~Derived() { cout << "Derived Destroyed\n"; } }; int main(){ Derived d; Base* bptr = new Derived(); delete bptr; // explicit delete call the destructor immediately bptr = new Derived(); // the object will be deleted by garbage collection // after program exits, and hence no destructor statement return 0; } Derived Destroyed (for “delete bptr”) Base Destroyed Derived Destroyed (for object d going out of scope) Base Destroyed
What is the Output? int main(){ A* z = new A; z->f(); delete z; A* x = new B; x->f(); delete x; A* y = new C; y->f(); delete y; return 0; } #include <iostream> using namespace std; class A { public: A() {} void f() {cout << "A::f()" << endl;} }; class B: public A { public: B() {} void f() {cout << "B::f()" << endl;} }; class C: public B { public: C() {} void f() {cout << "C::f()" << endl;} }; 46
Output: A::f() A::f() A::f() 47
If we add ‘virtual’ to class A? class A { public: A() {} virtual void f() {cout << "A::f()" << endl;} }; 49
Output: A::f() B::f() C::f() 50