Download presentation
Presentation is loading. Please wait.
Published byWhitney Black Modified over 9 years ago
1
Polymorphism Dr. Leon Jololian
2
Dr.Jololian2 class Person { private: string name; int age; public: Person(string na, int ag); Person(string na); string getName(); int getAge(); void setName(string na); void setAge(int ag); void print(); };
3
Dr.Jololian3 class Student : public Person { private: string major; float gpa; public: Student(string na, int ag, string ma, float gp); string getMajor() { return major; } float getGpa() { return gpa; } void setMajor(string ma) { major = ma; } void setGpa(float gp) { gpa = gp; } void print(); };
4
Dr.Jololian4 #include "Student.h" void main() { Person per("John Doe", 18); per.print(); Student stu("Jane Smith", 19, "Business", float(3.8)); stu.print(); Person* p; p = &per; p->setAge(21); p->print(); p = &stu; p->setAge(20); p->print(); }
5
Dr.Jololian5 Name: John Doe Age: 18 Name: Jane Smith Age: 19 Major: Business GPA: 3.8 Name: John Doe Age: 21 Name: Jane Smith Age: 20 Output
6
Dr.Jololian6 class Person { private: string name; int age; public: … virtual void print(); }; class Student : public Person { private: string major; float gpa; public: … void print(); }; Virtual Function
7
Dr.Jololian7 Output Name: John Doe Age: 18 Name: Jane Smith Age: 19 Major: Business GPA: 3.8 Name: John Doe Age: 21 Name: Jane Smith Age: 20 Major: Business GPA: 3.8
8
Dr.Jololian8 class Employee : public Person { private: string title; float salary; public: Employee( string n, int a, string t, float s); //... void print(); };
9
Dr.Jololian9 Employee::Employee(string n, int a, string t, float s) : Person(n, a) { title = t; salary = s; } void Employee::print(){ Person::print(); cout << "Title: " << title << endl; cout << "Salary: " << salary << endl<<endl; }
10
Dr.Jololian10 void main() { Employee emp("Bill Johnson", 25, "Programmer", float(54325.0)); Person* p; emp.print(); p = &emp; p->print(); }
11
Dr.Jololian11 Output Name: Bill Johnson Age: 25 Title: Programmer Salary: 54325 Name: Bill Johnson Age: 25 Title: Programmer Salary: 54325
12
Dr.Jololian12 class Undergrad : public Student { private: int year; public: Undergrad(string n, int a, string m, float g, int y); void print(); };
13
Dr.Jololian13 Undergrad::Undergrad(string n, int a, string m, float g, int y) : Student(n, a, m, g) { year = y; } void Undergrad::print() { Student::print(); cout << "Year: " << year << endl; }
14
Dr.Jololian14 void main() { Person* p; Undergrad und("Tom Jones", 19, "Accounting", float(3.99), 3); und.print(); p = &und; p->print(); }
15
Dr.Jololian15 Output Name: Tom Jones Age: 19 Major: Accounting GPA: 3.99 Year: 3 Name: Tom Jones Age: 19 Major: Accounting GPA: 3.99 Year: 3
16
Dr.Jololian16
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.