// This demonstrates the polymorphic behavior // of classes with virtual functio
ID: 664956 • Letter: #
Question
// This demonstrates the polymorphic behavior
// of classes with virtual functions.
#include "inheritance.h"
#include <iostream>
using namespace std;
int main()
{
// Create an array of Person objects.
const int NUM_PEOPLE = 5;
Person *arr[NUM_PEOPLE] =
{
new TFaculty("Indiana Jones", ARCHEOLOGY, "Dr."),
new Student("Thomas Cruise", COMPUTER_SCIENCE, NULL),
new Faculty("James Stock", BIOLOGY),
new TFaculty("Sharon Rock", BIOLOGY, "Professor"),
new TFaculty("Nicole Eweman", ARCHEOLOGY, "Dr.")
};
// Print the names of the Person objects.
for (int k = 0; k < NUM_PEOPLE; k++)
{
cout << arr[k]->getName() << endl;
}
return 0;
}
#include <string>
using namespace std;
enum Discipline { ARCHEOLOGY, BIOLOGY, COMPUTER_SCIENCE };
enum Classification { FRESHMAN, SOPHOMORE, JUNIOR, SENIOR };
// The Person class is modified to make getName
// a virtual function.
class Person{
protected:
string name;
public:
Person() { setName(""); }
Person(string pName) { setName(pName); }
void setName(string pName) { name = pName; }
// Virtual function.
virtual string getName() { return name; }
};
class Student:public Person
{
private:
Discipline major;
Person *advisor;
public:
Student(string sname, Discipline d, Person *adv)
: Person(sname)
{
major = d;
advisor = adv;
}
void setMajor(Discipline d) { major = d; }
Discipline getMajor() { return major; }
void setAdvisor(Person *p) { advisor = p; }
Person *getAdvisor() { return advisor; }
};
class Faculty:public Person
{
private:
Discipline department;
public:
Faculty(string fname, Discipline d) : Person(fname)
{
department = d;
}
void setDepartment(Discipline d) { department = d; }
Discipline getDepartment( ) { return department; }
};
class TFaculty : public Faculty
{
private:
string title;
public:
TFaculty(string fname, Discipline d, string title)
: Faculty(fname, d)
{
setTitle(title);
}
void setTitle(string title) { this->title = title; }
// Virtual function
virtual string getName( )
{
return title + " " + Person::getName();
}
};
Polymorphism and Virtual Functions
Get the source code and Compile main.cpp and inheritance.h as a project and
Add a retiree faculty class with retirement date as a data member.
class RFaculty : public Faculty
{
}
Explanation / Answer
#include <ctime>
using namespace std;
class RFaculty : public Faculty
{
private:
time_t retirementDate;
public:
RFaculty(string fname,Discipline d,time_t rDate) : Faculty(fname,d)
{
retirementDate = rDate;
}
time_t getRetDate()
{
return retirementDate;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.