Point a derived-class pointer at a base class - C++ Class

C++ examples for Class:Inheritance

Description

Point a derived-class pointer at a base class

#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;
};
    
    
int main(int argc, const char *argv[]) {
  Employee commissionEmployee("Sue", "Jones", "222-22-2222", 10000,
    .06);
  BasePlusEmployee *basePlusEmployeePtr = 0;
    
  // aim derived-class pointer at base-class object
  // Error: a Employee is not a BasePlusEmployee
  //basePlusEmployeePtr = &commissionEmployee;
  return 0;
}

Related Tutorials