#include #include #include using namespace std; class Person { public: Person(string _name) { name = _name; } string name; virtual void Greet() { cout << "Hi! My name is " << name << "." << endl; } }; class Doctor : public Person { public: Doctor(string _name, int _rating) : Person(_name) { rating = _rating; } int rating; void Reassure() { cout << "You probably won't die today." << endl; } virtual void Greet() { cout << "Hi! My name is " << name << ", I'm a doctor, you can trust me." << endl; } }; int main() { // a regular person Person * p1 = new Person("Stan"); p1->Greet(); // a doctor, who also is-a person Doctor * p2 = new Doctor("Abby", 5); p2->Greet(); p2->Reassure(); // a doctor, who also is-a person, referred to as a person Person * p3 = p2; p3->Greet(); // THIS WOULD ERROR: p3 is a person pointer, and a person can't reassure // (we don't know that the person p3 is pointing at is actually a doctor) //p3->Reassure(); // Polymorphism // Everone in the array is referred to as a person Person * a[10]; a[0] = new Person("Chelsea"); a[1] = new Doctor("Villian", 3); a[2] = new Person("Bowwow"); // However, Greet is virtual, so it will call Person::Greet or Doctor::Greet as appropriate for (int i = 0; i < 3; i++) { a[i]->Greet(); } return 0; }