C++ examples for Class:Polymorphism
Demonstrate Polymorphism, virtual functions and dynamic binding.
#include <string> using namespace std; class Employee { public: Employee(const std::string&, const std::string&, const std::string&, double, double); void setFirstName(const std::string&); std::string getFirstName() const; void setLastName(const std::string&); std::string getLastName() const; void setSocialSecurityNumber(const std::string&); std::string getSocialSecurityNumber() const; void setGrossSales(double); double getGrossSales(); void setCommissionRate(double); double getCommissionRate() const; virtual double earnings() const; virtual void print() const; private: std::string firstName; std::string lastName; std::string socialSecurityNumber; double grossSales; double commissionRate; }; class BasePlusEmployee : public Employee { public: BasePlusEmployee(const std::string&, const std::string&, const std::string&, double = 0.0f, double = 0.0f, double = 0.0f); void setBaseSalary(double); double getBaseSalary() const; virtual double earnings() const; virtual void print() const; private: double baseSalary; }; #include <iomanip> #include <iostream> int main(int argc, const char *argv[]) { // create base-class object Employee commissionEmployee("Sue", "Jones", "222-22-2222", 10000,.06); // create base-class pointer Employee *commissionEmployeePtr = 0; // create derived-class object BasePlusEmployee basePlusEmployee("Bob", "Lewis", "333-33-3333", 5000, .04, 300); // create dervied-class pointer BasePlusEmployee *basePlusEmployeePtr = 0; // set floating-point output formatting std::cout << std::fixed << std::setprecision(2); // output objects using static binding std::cout << "Invoking print function on base-class and derived-class " << "\nobject with static binding\n\n"; commissionEmployee.print(); // static binding std::cout << "\n\n"; basePlusEmployee.print(); // static binding // output objects with dynamic binding std::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; std::cout << "\n\nCalling virtual function print with derived-class " << "pointer\nto derived-class object invokes derived-class " << "print function:\n\n"; basePlusEmployeePtr->print(); // aim base-class pointer at derived-class object and print commissionEmployeePtr = &basePlusEmployee; std::cout << "\n\nCalling virtual function print with base-class pointer" << "\nto derived-class object invokes derived-class " << "print function:\n\n"; // polymorphism; invokes BasePlusEmployee's print; // base-class pointer to derived-class object commissionEmployeePtr->print(); std::cout << std::endl; return 0; }