// CS1621 // Demo of simple polymorphism in C++. Compare to poly.java and the related // class files // Note: After class on Monday, November 28, I added destructors to this // program, so you could see the sequence of calls. I recommend running // this yourselves to see what happens. #include #include using namespace std; class People { private: string name; int age; public: People() { cout << "People default constructor: " << this << endl;} People(string s, int i) { name = s; age = i; cout << "People constructor: " << this << endl; } virtual void Insert(ostream& ostr) { ostr << "Name: " << name << " Age: " << age; } virtual ~People() { cout << "People destructor: " << this << endl; } }; class Student: public People { private: string major; double gpa; public: Student(string s, int i, string mymajor, double mygpa): People(s, i) { major = mymajor; gpa = mygpa; cout << "Student constructor: " << this << endl; } virtual void Insert(ostream& ostr) { People::Insert(ostr); ostr << " Major: " << major << " GPA: " << gpa; } ~Student() { cout << "Student destructor: " << this << endl; } }; class Worker: public People { private: double salary; public: Worker(string s, int i, double mysalary): People(s, i) { salary = mysalary; cout << "Worker constructor: " << this << endl; } virtual void Insert(ostream& ostr) { People::Insert(ostr); ostr << " Salary: " << salary; } ~Worker() { cout << "Worker destructor: " << this << endl; } }; int main() { // To utilize polymorphism in C++, pointers (or references) must be used People ** P = new People * [6]; P[0] = new People("Herb", 25); P[1] = new Worker("Bart", 60, 85000); P[2] = new Worker("Zeke", 32, 45000); P[3] = new Student("Bill", 20, "CS", 3.5); P[4] = new Student("Mary", 18, "English", 3.8); P[5] = new People("Alice", 40); for (int i = 0; i < 6; i++) { P[i] -> Insert(cout); cout << endl; } cout << endl; for (int i = 0; i < 6; i++) delete P[i]; // Now lets do the same thing with static objects and no pointers. The // syntax is still legal, but note that the function called is now always // the one from the People class, since the array is an array of People People P2[6]; P2[0] = People("Herb", 25); P2[1] = Worker("Bart", 60, 85000); P2[2] = Worker("Zeke", 32, 45000); P2[3] = Student("Bill", 20, "CS", 3.5); P2[4] = Student("Mary", 18, "English", 3.8); P2[5] = People("Alice", 40); for (int i = 0; i < 6; i++) { P2[i].Insert(cout); cout << endl; } }