In: Computer Science
Refactor the following classes so they are both derived from a base class called Person. Write the code for the new base class as well. Try to avoid repeating code as much as possible. Write the classes so that any common methods can be invoked through a pointer or reference to the base class.
#include <string>
#include <cmath>
using namespace std;
class Student
{
private:
string name;
int age;
int studyYear;
public:
Student(string,int,int);
void study();
void eat();
};
Student::Student(string _name, int _age, int _studyYear)
{
name = _name;
age = _age;
studyYear = _studyYear;
}
void Student::study()
{
cout << name << " is studying."
<<endl;
}
void Student::eat()
{
cout << name << " is eating."
<<endl;
}
class Doctor
{
private:
string name;
int age;
int salary;
public:
Doctor(string,int,int);
void checkup();
void eat();
};
Doctor::Doctor(string _name, int _age, int _salary)
{
name = _name;
age = _age;
salary = _salary;
}
void Doctor::checkup()
{
cout << name << " is checking up."
<<endl;
}
void Doctor::eat()
{
cout << name << " is eating."
<<endl;
}
#include <iostream>
#include <string>
using namespace std;
class Person
{
protected:
string name;
int age;
public:
Person(string,int);
void eat();
};
//implementation section for Person
Person::Person(string _name, int _age) // constructor
{
name = _name;
age = _age;
}
void Person::eat()
{
cout << name << " is eating." <<endl;
}
// declaration section where Student is derived from Person
class Student : public Person
{
protected:
int studyYear;
public:
Student(string,int,int);// constructor
void study();
void eat();
};
Student::Student(string _name, int _age, int _studyYear)
{
name = _name;
age = _age;
studyYear = _studyYear;
}
void Student::study()
{
cout << name << " is studying in his
"<<_studyYear <<" year" <<endl;
}
void Student::eat()
{
cout << name << " is eating." <<endl;
}
// declaration section where Doctor is derived from Person
class Doctor : public Person
{
protected:
int salary;
public:
Doctor(string,int,int);
void eat();
void checkup();
};
Doctor::Doctor(string _name, int _age, int _salary)
{
name = _name;
age = _age;
salary = _salary;
}
void Doctor::checkup()
{
cout << name << " is checking up." <<endl;
}
void Doctor::eat()
{
cout << name << " is eating." <<endl;
}
Comment down for any queries
Please give a thumbs up