Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Lecture 6 - 7 OOP Course. 2 6. Inheritance Basics Shape.

Similar presentations


Presentation on theme: "1 Lecture 6 - 7 OOP Course. 2 6. Inheritance Basics Shape."— Presentation transcript:

1 1 Lecture 6 - 7 OOP Course

2 2 6. Inheritance Basics Shape

3 3Motivation Suppose we want to computerize our personnel records We start by identify the two main types of employees we have: class Engineer { char* name; short year_born; short department; int salary; char* degrees; public: void give_raise( int how_much); //... }; class SalesPerson { char* name; short year_born; short department; int salary; double *comission_rate; public: void give_raise( int how_much); //... };

4 4 Identifying the Common Part class SalesPerson: Employee { double *comission_rate; //... }; class Employee { char* name; short year_born; short department; int salary; public: void give_raise( int how_much); //... }; class Engineer: Employee { char* degrees; //... }; C solution: struct Engineer { struct Employee E; char *degree; /* ….. */ };

5 5 What is Inheritance BehaviorData subclassextention superclass The Behavior and the Data associated with a subclass are an extention of the properties of the superclass EngineerSalesPerson Employee Engineer and SalesPerson extends, each in its own way, the data and behavior of Employee Employee Identifying the Employee abstraction, helps us define more types easily Class Employee Class Manager class Manager: Employee { char* degrees; //... };

6 6 Expanding the original class Specializing the original class Inheritance Concept RealNumber ComplexNumber ImaginaryNumber Rectangle Triangle Shape Point Circle real imag real imag 3D-Point

7 7 Inheritance Mechanism classinheritbase class derived classA class may inherit from a base class, in which case the inheriting class is called a derived class classmethods inheriteddataA class may override inherited methods (member functions), but cannot override inherited data

8 8 What is it Used For? Software reusabilitySoftware reusability –Allows you to modify or extend a package somebody gave you without touching the package’s code –Saves programming time –Smaller programs Consistency of interfaceConsistency of interface –Saves user time –Interface to similar objects is similar –An overridden function must have the same return type PolymorphismPolymorphism –Different objects behave differently as a response to the same message Least important More important Most important

9 9 Inheritance Example TimeTime is the base class ExtTimeExtTime is the derived class ExtTimeTime

10 10 Class Time Specification class Time{protected: int hrs; int mins; intsecs; public: Time (int initH, int initM, int initS): hrs(initH), mins(initM), secs(initS){}; void Set (int h, int m, int s ){…}; void Increment () {secs++;}; void Print () const{ cout << hrs << “:” << mins << “:” << secs;}; }; int main()‏ { Time *t = new Time(8,8,8); t->Print(); // 08:08:08 }

11 11 Class Interface Diagram Protected data: hrs mins secs Set Increment Print Time Class Time

12 12 Derived Class ExtTime #include “time.h” enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT}; : public Time class ExtTime: public Time{ ZoneType zone; public: ExtTime (int initH, int initM, int initS, ZoneType :Time(initH, initM, initS) initZ):Time(initH, initM, initS), zone(initZ){}; void Set (int h, int m, int s, ZoneType timeZone){ Time :: Set (h, m, s); zone = timeZone;}; void Print ( )const { string zoneString[8] = {“EST”, “CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT”} ; Time::Print ( ); cout << “ “ << zoneString[zone] << endl;}; };

13 13 Class Interface Diagram Protected data: hrs mins secs ExtTime class Set Increment Print Time Set Increment Print ExtTime Private data: zone

14 14 Points of Interest public inheritanceWe used public inheritance, later we will talk about other kinds of inheritance Constructors are not inherited ExtTime TimeConstructors are not inherited. If we haven’t defined constructor for ExtTime, then the compiler would try to generate an empty default constructor and fail in doing so since there is no default constructor of the base class Time sub-object initialization list ExtTimeThe initialization of the sub-object of the inherited class Time must be done in the initialization list of the constructor of the derived class ExtTime ExtTime (int initH, int initM, int initS, ZoneType initZ):Time(initH, initM, initS), zone(initZ){}; class ExtTime: public Time{ // …

15 15 Points of Interest cont. ExtTimePrintExtTime overrides Print method ExtTimeIncrement TimeSince ExtTime doesn’t override the Increment method, the following calls the method from Time class An overridden function can be called as follows: class ExtTime: public Time{ // … void Print ( )const; //overridden ExtTime extTime = (8,8,8,EST); extTime.Increment(); // … Time::Print(); cout << “ “ <<zoneString[zone]<<endl;

16 16 Working with ExtTime #include “exttime.h” int main()‏ { ExtTime thisTime ( 8, 35, 0, PST ); ExtTime thatTime (10, 10, 10, EST ); thatTime.Print( ); // outputs 10:10:10 EST thatTime.Set (16, 49, 23, CDT) ; thatTime.Print( ); // outputs 16:49:23 CDT thisTime.Increment ( ) ; thisTime.Print ( ); // outputs 08:35:02 PST }

17 17 Access Control Over the Members Two levels of access control over class members –class definition –inheritance type class Point{ protected: protected: int x, y; public: public: void set(int a, int b); } public class Circle : public Point{ … }

18 18 Access Control in Public inheritance privatebase classnot derived classprivate members of the base class are not accessible to the derived class –Otherwise, privacy is completely violate publicbase classpublic members of the base class are accessible to anyone protectedbase class derived classesprotected members of the base class are accessible to derived classes only class Time{ proteced: int hrs; int mins; int secs; //...

19 19 Consider a class D derived from a base class B – –With private inheritance (default mode), the public and protected members of B can be used only by member functions and friends of D – –With protected inheritance, the public and protected members of B can be used only by member functions and friends of D and by member functions and friends of classes derived from D – –With public inheritance, the public and protected members of B can be used only by any function Access Rights of Derived Classes publicprotectedprivatepublic protected privateprotected privatepublicprotectedprivate Type of Inheritance Access Control for Members Access from external functions:

20 20 Class Derivation A BCD class A { private: int private_a; protected: int protected_a; public: int public_a; }; class B : private A { public: B(){ private_a = 2; // Error! protected_a = 2; public_a =2; }; class C : protected A { public: C(){ private_a = 3; // Error! protected_a = 3; public_a = 3; }; class D : public A { public: D(){ private_a = 4; // Error! protected_a = 4; public_a =4; }; int main()‏ { B b; C c; D d; b.public_a=10; // Error! c.public_a=10; // Error! d.public_a=10; return 0; }

21 21 class A { public: A ( ) {cout<< “A::A()”<<endl;} A (int a){ cout<<“A::A(int a)”<<endl;} } Constructor Rules for Derived Classes class C : public A { public: C (int c): A(c) C (int c): A(c){ cout<<“C::(int c)”<<endl;} } Option 1: class C : public A { public: C (int c) C (int c){ cout<<“C::(int c)”<<endl;} } Option 2: C test(1); // A::A(int a)‏ // C::C(int c)‏ C test(1); // A::A()‏ // C::C(int c)‏

22 22 Is-A Relationship is aDerived class is a (more specialized) version of the base class: –Manager is an Employee –ExtTime is a time –Rectangle is a Shape Thus, any function taking the class B (base class) as an argument, will also accept class D (derived class from B)‏ class Stack {...}; int SumAndPop(Stack& s){...} class MultiStack: public Stack { public: void popk(int k) {...} }; int main(){ MultiStack multiStack; int a = SumAndPop(multiStack); //... }

23 23 Is-A Relationship cont. Person p; Worker w; p.GetName(); // OK w.GetName(); // OK p.CalculateSal(); // ERROR! w.CalculateSal(); // ok Class Person Class Worker name GetName()‏ salary CalculateSal()‏ WorkerPerson Worker is a Person but not vice-versa!

24 24 Summary What we have seen so far code reuse –Inheritance for code reuse reasons Is-A –Reflects a relationship of Is-A derived base class –Inheritance means that the derived inherits its base class characteristics derived class –The derived class can add to this characteristics of its own Class Person Class Worker name GetName()‏ salary CalculateSal()‏

25 25 Summary cont. inherited derived –We can invoke all inherited characteristics through the derived –For instance, we can ask the worker what is his name, even though he does not implement such a method –The compiler resolves the call to Person::GetName()‏ –If we implement such a method at the Worker class, the compiler will call to Worker::GetName()‏ –Protected –Protected access keyword has been introduced Worker w; w.GetName();

26 26 7. Polymorphic Inheritance Animal

27 27 Lets Continue to Polymorphic Inheritance Suppose we have a container of Employees We would like to iterate over all employees, without knowing which specific kind they are, and ask them to calculate their salary (call their CalcSalary() method)‏ Each type has its own calculation algorithm, based on different considerations Each object will invoke its relevant CalcSalary(), depending on its type Class Employee Class SalesPersonClass ExecutiveClass Administrative m_salary v. CalcSalary()‏ m_salesm_performance

28 28 Example We want each element in the container to call its own CalcSalary() method as a function of the real object Employee  Employee::CalcSalary()‏ SalesPerson  SalesPerson::CalcSalary()‏ Executive  Executive::CalcSalary()‏ Administrative  Administrative::CalcSalary()‏ Executive Administrative Executive Sales Person Employee* employees[100];

29 29 Static and dynamic binding In object-oriented programming languages in most cases the variables are bound to a specific type at compile time –Static binding Dynamic binding –The type of the variable can change at run time –Using pointers to classes related by inheritance –Can be dangerous in some cases Executive exec; Employee* emp = &exec;

30 30 Example class Employee { public: void CalcSalary (); }; class SalariedEmployee: public Employee{ public: void CalcSalary (); }; Employee *ep; ep = new SalariedEmployee; ep->CalcSalary(); Employee The function in Employee is called! virtual functionTo avoid that we have to declare CalcSalary() as a virtual function (virtual is a special keyword)‏

31 31 Virtual Functions Definition: –Member function prefaced by the virtual specifier. –Compiler generates the code that will select the appropriate function at runtime virtualvirtual specifier needs to appear in the base class only –However, typically specified also in subclasses class Employee { public: virtual void CalcSalary (); }; class SalariedEmployee:public Employee{ public: virtual void CalcSalary (); };

32 32 Examples Any non-static member function except a constructor can be virtual Virtual functions can also be friends of other classes Some compilers require the class destructor to be virtual if a class contains any virtual functions Employee *p0 = new Employee; Employee *p1 = new SalariedEmployee; p0->CalcSalary(); // calls Employee::CalcSalary()‏ p1->CalcSalary(); // calls SalariedEmployee::CalcSalary()‏

33 33 Virtual Functions Calls on object itself resolved statically - b.y(); If non-virtual there, resolve statically - ap->x(); If virtual there, resolve dynamically - ap->y(); Caller can force static resolution of a virtual function - ap->A::y(); int main () { B b; A *ap = &b; B *bp = &b; b.x (); b.y (); bp->x (); bp->y (); ap->x (); ap->y (); ap->A::y(); return 0; }; Output: B:x B:y B:x B:y A:x B:y A:y class A { public: void x() {cout<<"A:x";}; virtual void y() {cout<<"A:y";}; }; class B : public A { public: void x() {cout<<"B:x";}; virtual void y() {cout<<"B:y";}; };

34 34 Combinations of virtual and non- virtual functions Non-virtual function can call virtual function class Employee { public: void Display() {CalcSalary();}; virtual void CalcSalary (); }; class SalariedEmployee:public Employee{ public: void Display() {CalcSalary();}; virtual void CalcSalary (); }; Employee *p0 = new SalariedEmployee; p0->Display(); // calls SalariedEmployee::CalcSalary();

35 35 Combinations of virtual and non- virtual functions Non-virtual function can call virtual function class Employee { public: virtual void Display() {CalcSalary();}; void CalcSalary (); }; class SalariedEmployee:public Employee{ public: virtual void Display() {CalcSalary();}; void CalcSalary (); }; Employee *p0 = new SalariedEmployee; p0->Display(); // calls Employee::CalcSalary();

36 36 Common Interface base class interfaceVirtual functions in the base class provide common interface for all of its derived classes class Employee { public: long GetDepartment(); long GetId(); virtual void Display(); virtual void Input(); virtual void CalcSalary(); private: long id; long deptNum; };

37 37 Example class Polygon { protected: int width, height; public: void setValues (int a, int b){ width=a; height=b; } virtual int area(){ retuen 0; } }; class Rectangle: public Polygon { public: int area () { return (width * height); } }; class Triangle: public Polygon { public: int area () { return (width * height / 2); } };

38 38 Example (cont.)‏ int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = &rect; Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5); ppoly2->set_values (4,5); cout area() << endl; // 20 cout area() << endl; // 10 return 0; }

39 39 Virtual Destructors Destructor preceded by the virtual specifier –Correct destructor must be called any class containing virtual functions should also have a virtual destructorIt is recommended that any class containing virtual functions should also have a virtual destructor BookItem needs a separate destructor to de- allocate the storage for title class Item { public: virtual ~Item(); //... }; class BookItem : public Item{ public: virtual ~BookItem(); private: char * title; };

40 40 Pure Virtual pure virtualThe Employee can define this method at the base class as pure virtual : virtual int Employee::CalcSalary() = 0; Meaning, Abstract Class –We cannot instantiate an object of this class – it is said to be an Abstract Class –It wants all inheriting classes to implement their own implementation –But we still can have pointers

41 41 Example class Polygon { protected: int width, height; public: void setValues (int a, int b){ width=a; height=b; } virtual int area()=0; }; class Rectangle: public Polygon { public: int area () { return (width * height); } }; class Triangle: public Polygon { public: int area () { return (width * height / 2); } };

42 42 Virtual Functions class A { public: virtual void x() = 0; virtual void y() = 0; }; class B : public A { public: virtual void x(); }; class C : public B { public: virtual void y(); }; int main () { A * ap = new C; ap->x (); ap->y (); delete ap; return 0; }; Abstract Base ClassA is an Abstract Base Class pure virtual functions –Declares pure virtual functions (=0)‏ Derived classes override pure virtual methods –B overrides x(), C overrides y()‏ Can’t instantiate class with declared or inherited pure virtual functions –A and B are abstract, C can be created Can still have a pointer to an abstract class type –Useful for polymorphism

43 43 Static Binding Vs. Dynamic Binding Static Binding –Function call is resolved during compile time –Call fixed value Dynamic Binding –During compile time we cannot know what address to jump to –It needs to be resolved during run-time –Depending on the type of the actual object This information is accessed via virtual pointer –Each object holds And via virtual table –Each class maintains

44 44 Dynamic Binding - Implementation Executive Administrative Executive Sales Person Executive Virtual Table Sales Person Virtual Table Executive::CalcSalary()‏ SalesPerson::CalcSalary()‏ Employee* employees[100];

45 45 Summary: Tips on Polymorphism base classesPush common code and variables up into base classes public inheritanceUse public inheritance for polymorphism Polymorphism depends on dynamic typing base-class pointer –Use a base-class pointer or reference if you want polymorphism virtual member functions –Use virtual member functions for dynamic overriding private inheritanceUse private inheritance only for encapsulation abstract base classesUse abstract base classes to declare interfaces Even though you don’t have to, label each virtual method (and pure virtual method) in derived classes

46 46 8. Multiple Inheritance

47 47 Let's recall What we have seen so far –Polymorphic inheritance For defining generic interface Accessing the concrete implementations via this interface The compiler implements code, which extracts during Run-Time the needed calling address Through a virtual pointer –Which usually point at the actual object And through a virtual table –Which holds the addresses of the virtual functions

48 48 Construction and Destruction Class Employee Class SalesPersonClass ExecutiveClass Administrative m_salary v. CalcSalary()‏ m_salesm_performance Let us recall the construction order and functionality –What is the order of “things” Let us see what happens during destruction –What is the order of “things” Can a destructor be virtual? Does it need to be virtual? When?

49 49 Multiple Inheritance Class Employee Class SalesPersonClass ExecutiveClass Administrative m_salary v. CalcSalary()‏ m_salesm_performance Class Student v. M()‏ Class Metargel v. CalcSalary()‏ v. M()‏ Class Person Sometimes it is desirable for a derived class to inherit features from more than one base class How is this represented in memory? What is the layout of the instance? Can you think of problems using this?

50 50 Syntax Teaching Assistant maintains the attributes and the methods associated with both base classes Student, and Employee class Metargel : public Student, public Employee { // … }

51 51 Polymorphic Assignment Metargel * myMetargel = new Metargel; Employee * E = myMetargel; //Legal as a Teaching Assistant //is-an Employee Student * S = myMetargel; //Legal as a Teaching Assistant //is-a Student

52 52 Problems with Multiple Inheritance Name Ambiguity:Name Ambiguity: –Similar names can be used for different operations in the base classes e.g. an employee might have an id_number and a student might also have an id_number field. –Both base classes might have a similar get_id() method –The compiler cannot determine which version to use in the Metargel class: the get_id() in the Employee class or the get_id () in the Student class compositionspecializationA common misuse of multiple inheritance is using it as composition rather than specialization (is-a): incorrect –The following is incorrect: class car: public Engine, public Transmission, public Wheels

53 53 Name Ambiguity Solution 1: Use a fully qualified function name: Metargel * myMetargel = new Metargel; cout << “ The TeachingAssistant is” << myMetargel -> Employee::get_id() << “\n”;

54 54 Name Ambiguity Solution 2: Redefine the ambiguous function in the new class and hide the qualified name in a method body: class Metargel : public Student, public Employee { public: string get_id(); public: string student_id(); } string Metargel ::get_id()‏ { return Employee::get_id(); } string Metargel ::student_id()‏ { return Student::get_id(); }

55 55 Virtual Inheritance - Motivation Class Employee Class SalesPersonClass ExecutiveClass Administrative m_salary v. CalcSalary()‏ m_salesm_performance Class Student v. M()‏ Class Metargel v. CalcSalary()‏ v. M()‏ Class Person m_name What if class student and class Employee both inherit from Person? How can this be dealt with?

56 56 Replicated Base Classes can not be directly inheritedThe same class can not be directly inherited more than once might be inherited indirectlyBase classes might be inherited indirectly more than once –due to a class inheritance hierarchy In our example suppose the following: class Employee : public Person {..} class Student : public Person {..} class Metargel : public Student, public Employee {..} Attributes from the Person class get inherited twice! –Metargel will have two m_name fields

57 57 D B Replicated Inheritance Recall that replicated inheritance does not share the same common grandparent even if they both derive from the same grandparent! If we have code like this in C++: class A { … }; class B: public A { … }; class C: public A { … };/* Derives from A but it isn’t shared!*/ class D: public B, public C { … }; This gives us the following situation: A BC A D A* a; B* b; C* c; D* d; b = d; // ok c = d; // ok a = b; // ok a = c; // ok a = d; //error ambiguous A C A

58 58 Virtual Inheritance Single instance within layout Class Employee Class SalesPersonClass ExecutiveClass Administrative m_salary v. CalcSalary()‏ m_salesm_performance Class Student v. M()‏ Class Metargel v. CalcSalary()‏ v. M()‏ Class Person

59 59 Virtual Base Classes virtualTo merge any common base classes into one single copy the inheritance should be written as virtual: class Employee: virtual public Person {..} class Student: virtual public Person {..} class TeachingAssistant : public Student, public Employee {..}

60 60 Virtual Inheritance Standard base classes –A members appear twice in D Virtual base classes class B : public virtual A { … } –Avoid duplication of base class members –Require additional pointers so that A part of B, C parts of object can be shared D B A BC D A C

61 61 Virtual Base Classes Metargel * myMetargel = new Metargel; Student * s = myMetargel; // Legal due to is-a // relationship Person * p = s; // Legal due to is-a relationship Employee * e = myMetargel;// Legal due to is-a // relationship Person * p1 = e; // Legal due to is-a relationship Person * p2 = myMetargel; // Legal only if Virtual // Inheritance is used so that the compiler knows which // version of person to use, error otherwise

62 62 Summary - Multiple Inheritance It is recommended to keep multiple inheritance to minimal usage –Due to complexity, which may arise –Due to misusage –You may use it, but please use it with care abstract classesmultiple inheritanceRecommended to use as many as possible abstract classes, and not multiple inheritance Make sure this really models your problem domain well


Download ppt "1 Lecture 6 - 7 OOP Course. 2 6. Inheritance Basics Shape."

Similar presentations


Ads by Google