90 likes | 238 Views
Lecture 12 – Inheritance. Inheritance Access to Class Members using Public Inheritance Graphics Package Example Polymorphism Polymorphism Example Abstract Classes. Inheritance. OOP = DA + Inheritance + Polymorphism Two mechanisms to build classes utilizing s/w reuse
E N D
Lecture 12 – Inheritance • Inheritance • Access to Class Members using Public Inheritance • Graphics Package Example • Polymorphism • Polymorphism Example • Abstract Classes
Inheritance • OOP = DA + Inheritance + Polymorphism • Two mechanisms to build classes utilizing s/w reuse • Composition – “has a” relationship class Employee { … Date birth; …}; • Inheritance – “is a” class Manager : public Employee { … }; • Inheritance involves “absorbing” of data and functions • base class defines common attributes and operations shared with all derived classes • derived class extends base class by adding its own data and member functions
Access to Class Members using Public Inheritance Can access public & protected members of base classes
Graphics Package (Cont’d) double radius double length double length double width getRadius () int n setRadius () getLength () draw() getN () getWidth () getLength () circleShape setSides () setN () draw() setLength () double x, y draw() rectShape ShapeColor c polyShape getX() double endX string text getY() double endY move() draw () getText () getColor () getEndX () setText () setColor () getEndY () draw() erase() setEndPoint () (factor commonality) textShape shape lineShape
Polymorphism • Polymorphism • “many forms” • Ensures appropriate method is called in inheritance hierarchy • shapePtr->draw (); • Make functions polymorphic by declaring virtual • virtual void draw (); • Virtual functions are dynamically bound (function called depends on type of object referenced at run time) • Must call virtual function using pointer or reference handles (shapePtr->draw ()) • Non-virtual functions are statically bound using type of handle
Employee Hierarchy class Employee { string name, id; public: virtual void displayEmployeeInfo () { cout << name; } }; class HourlyEmployee : public Employee { float rate; public: virtual void displayEmployeeInfo () { Employee::displayEmployeeInfo (); cout << rate; }; };
Polymorphism (vtables) Two objects derived from Employee p->displayEmployeeInfo (); // 3 indirections: ptr to // object, object to vtbl, // then vtbl to method