0

So right now I have to call a specific print function based on which class the "Employee" is a part of.

My parent class print function in "Employees.cpp":

void Employees::printEmployee() const{ cout<<"Name: "<<employeeName<<endl; cout<<"Salary:"<<employeeSalary<<endl; cout<<"Employee ID: "<<employeeID<<endl; cout<<"Employee Class: "<<employeeClass<<endl<<endl; } 

and an example of a child class print functpion is my "Chef.cpp" print function:

void Chef::printChef() const{ cout<<"Name: "<<employeeName<<endl; cout<<"Salary: $"<<calculateSalary()<<endl; cout<<"Employee ID: "<<employeeID<<endl; cout<<"Employee Class: "<<employeeClass<<endl; cout<<"Share Perecent: "<<chefSharePercent<<"%"<<endl; cout<<"Chef's Specialty: "<<chefSpecialty<<endl<<endl; } 

The functions of "Chef.cpp" are definied in "Chef.h" which looks like so:

#ifndef CHEF_H_ #define CHEF_H_ #include <string> #include "employee.h" using namespace std; class Chef : public Employees{ public: Chef(); Chef(double percent, string specailty); void setPercent(double percent); void setSpecialty(string specailty); double getPerecent() const; string getSpecialty() const; double calculateSalary() const; void printChef() const; private: double chefSharePercent; string chefSpecialty; }; #endif 

Is there any way to have just one print function which will print the appropriate members of each class. For example, My chef child class has all the same attributes as the parent "Employees" but in addition has a "Share Percent" and "Chef Specialty" member. I have 2 other child classes with class specific members as well.

Thanks.

3
  • Possible duplicate of Virtual function inheritance. Calling this a dupe is stretching things a little, but this is what you want to do, and there is no point to going over this again. Commented Apr 12, 2016 at 21:09
  • More useful information here: isocpp.org/wiki/faq/virtual-functions Commented Apr 12, 2016 at 21:12
  • printing should not be a member functions. Commented Apr 12, 2016 at 21:13

1 Answer 1

-1

You should learn about virtual methods. And Pure virtual methods. Take a look at this and let me know if this helps! http://www.thegeekstuff.com/2013/06/cpp-virtual-functions/ http://www.cplusplus.com/doc/tutorial/polymorphism/

Sign up to request clarification or add additional context in comments.

3 Comments

This is not really an answer, This would be better left as a comment on the question.
Perfect, this is exactly what I was looking for! Thank you, it works great!
I agree with the comment by @callyalater. You should expand the post by including code that specifically solves the OP's problem.