// virtual.cpp // An example of virtual functions and dynamic dispatch. // Taken from an example in the lecture slides for CSE 143. #include using namespace std; class person { public: virtual void walk() = 0; virtual void run() {cout << "Person running" << endl;} }; class student : public person { public: void enroll() {cout << "Student enrolls" << endl;} /* BAD STYLE */ virtual void walk() {cout << "Student walks" << endl;} }; class freshman : public student { public: void enroll() {cout << "Freshman enrolls" << endl;} virtual void run() {cout << "Freshman runs" << endl;} }; int main() { // COMPILE-TIME ERROR: // "cannot instantiate abstract class person" // person paula; student* stu = new freshman(); stu->enroll(); student sara = *stu; /* BAD STYLE */ sara.run(); person* pp = stu; pp->run(); pp->walk(); // COMPILE-TIME ERROR: // "cannot convert from 'class person*' to 'class freshman*' // freshman* fred = pp; // COMPILE-TIME ERROR // Invalid because previous line is invalid // fred->enroll(); return 0; } /* OUTPUT (take directly from the output screen) * * Student enrolls * Person running * Freshman runs * Student walks * */