Implement the Teacher class constructor using Base-Class Initializer syntax. Wri
ID: 3532955 • Letter: I
Question
Implement the Teacher class constructor using Base-Class Initializer syntax. Write the C++ code creating a polymorphic vector of type Employee, which can contain both Employee and Teacher objects, yet avoid slicing of Teacher objects. Add one Employee object and one Teacher object to the vector. Because the vector is of type Employee, what changes would have to be made to the class definitions so that, an Employee or Teacher object in the vector will access the correct getSalary() and setSalary () member functions?Explanation / Answer
// here is the code that will fullfill you requirenment
// for ans c:-- we just have to declare getSalyary() and setSalary() functions to be virtual at Employee // class, i have already made all the changes just check it
#include<iostream>
#include <vector>
using namespace std;
class Employee
{
public:
Employee(string n,float s,string p);
void setName(string s);
string getName() const;
virtual void setSalary(float s);
virtual float getSalary() const;
void setPhone(string p);
string getPhone() const;
private:
string name;
float salary;
string phone;
};
Employee:: Employee(string n,float s,string p)
{
name=n;
salary=s;
phone=p;
}
void Employee:: setName(string s)
{
name=s;
}
string Employee:: getName() const
{
return name;
}
void Employee:: setSalary(float s)
{
salary=s;
}
float Employee:: getSalary() const
{
return salary;
}
void Employee::setPhone(string p)
{
phone=p;
}
string Employee::getPhone() const
{
return phone;
}
class Teacher: public Employee
{
public:
Teacher(string n,float s,string p,string dept);
void setDeapartment(string d);
string getDepartment()const;
void setSalary(float s);
float getSalary() const;
private:
string department;
};
Teacher::Teacher(string n,float s,string p,string dept):Employee(n,s,p)
{
department =dept;
}
void Teacher::setDeapartment(string d)
{
department=d;
}
string Teacher::getDepartment()const
{
return department;
}
void Teacher::setSalary(float s)
{
Employee::setSalary(s);
}
float Teacher::getSalary() const
{
return Employee::getSalary();
}
int main()
{
vector<Employee*> v;
Employee e("walter",50000.00,"+91349875463");
Teacher t("pointing",60000.00,"+9123456789","computer science");
v.push_back(&e);
v.push_back(&t);
cout<<"--------------------------employee record------------------------- ";
cout<<"name: "<<v.at(0)->getName().data()<<endl;
cout<<"salary: "<<v.at(0)->getSalary()<<endl;
cout<<"phone number: "<<v.at(0)->getPhone().data()<<endl;
cout<<"--------------------------Teacher record------------------------- ";
cout<<"name: "<<v.at(1)->getName().data()<<endl;
cout<<"salary: "<<v.at(1)->getSalary()<<endl;
cout<<"phone number: "<<v.at(1)->getPhone().data()<<endl;
system("pause");
return 0;
}