In: Computer Science
Give an example of inheritance, you must have a parent and child and test program with at least one variable in each and setters and getters and constructors. The test program must test all the methods.
#include <iostream>
using namespace std;
class Person // base class
{
private:
string firstName;
string lastName;
string honorific;
public:
//constructor
Person(string firstName,string lastName,string
honorific)
{
this->firstName =
firstName;
this->lastName = lastName;
this->honorific =
honorific;
}
//set and get methods
void setFirstName(string firstName)
{
this->firstName =
firstName;
}
string getFirstName()
{
return firstName;
}
void setLastName(string lastName)
{
this->lastName = lastName;
}
string getLastName()
{
return lastName;
}
void setHonorific(string honorific)
{
this->honorific = honorific;
}
string getHonorific()
{
return honorific;
}
void display()
{
cout<<honorific<<"
"<<firstName<<" "<<lastName;
}
~Person() // destructor
{
cout<<"\ndestructor of
person";
}
};
class Student : public Person // derived class
{
private:
string courseName;
public:
Student(string firstName,string lastName,string
honorific,string
courseName):Person(firstName,lastName,honorific)
{
this->courseName =
courseName;
}
void setCourseName(string courseName)
{
this->courseName =
courseName;
}
string getCourseName()
{
return courseName;
}
void display()
{
Person::display();
cout<<"\nStudying in course :
"<<courseName;
}
~Student()
{
cout<<"\ndestructor of
student";
}
};
int main() {
Student st("Harris","Johnson","Dr.","Masters of
Cardiology");
st.display();
return 0;
}
Output:
Dr. Harris Johnson Studying in course : Masters of Cardiology destructor of student destructor of person
Do ask if any doubt. Please up-vote.