Lecture 6 - 7 OOP Course 1 6.

Lecture 6 - 7 OOP Course 1 6.

Lecture 6 - 7 OOP Course 1 6. Inheritance Basics Shape 2 Motivation 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); // ... }; 3 Identifying the Common Part C solution: struct Engineer {

struct Employee E; char *degree; /* .. */ }; class Employee { char* name; short year_born; short department; int salary; public: void give_raise( int how_much); // ... }; class Engineer: Employee { char* degrees; // ... };

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

5 Inheritance Concept Expanding the original class Shape Rectangle Point Circle Triangle 3D-Point Specializing the original class ComplexNumbe r real RealNumbe

r real imag ImaginaryNumber imag 6 Inheritance Mechanism A class may inherit from a base class, class in which case the inheriting class is called a derived class A class may override inherited methods (member functions), but cannot override inherited data 7 Least important

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

Inheritance Example Time Time is the base class ExtTime is the derived class ExtTime 9 Class Time Specification class Time{ protected: int hrs; int mins; int secs; 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 } 10 Class Interface Diagram Class Time Time Set Increment Print Protected data: hrs mins

secs 11 Derived Class ExtTime #include enum time.h ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT}; class ExtTime: public Time{ Time ZoneType zone; public: ExtTime (int initH, int initM, int initS, ZoneType initZ):Time(initH, initM, initS), 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;}; }; 12 Class Interface Diagram ExtTime class ExtTime Time Set Set Increment

Increment Print Print Private data: zone Protected data: hrs mins secs 13 Points of Interest We used public inheritance, inheritance later we will talk about other kinds of inheritance class //

ExtTime: public Time{ Constructors are not inherited. inherited If we havent defined constructor for ExtTime, 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 The 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){}; 14

Points of Interest cont. ExtTime overrides Print method class ExtTime: public Time{ // void Print ( )const; //overridden Since ExtTime doesnt override the Increment method, the following calls the method from Time class ExtTime extTime = (8,8,8,EST); extTime.Increment(); // An overridden function can be called as follows: // Time::Print(); cout << <

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.Increment ( ) ; thisTime.Print ( ); // outputs 08:35:02 PST } 16 Access Control Over the Members Two levels of access control over class

members class definition inheritance type class Point{ protected: int x, y; public: void set(int a, int b); } class Circle : public Point{ } 17 Access Control in Public inheritance private members of the base class are not accessible to the derived class Otherwise, privacy is completely violate public members of the base class are accessible to anyone protected members of the base class are accessible to derived classes only

class Time{ proteced: int hrs; int mins; int secs; // ... 18 Access Rights of Derived Classes Access from external functions: Access Control for Members Type of Inheritance private protected public private private

private private protected private protected protected public private protected public 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 19

can be used only by any function Class Derivation A B C int main() { B b; C c; D d; b.public_a=10; c.public_a=10; d.public_a=10; return 0; } D // Error! // Error!

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; }; }; 20 Constructor Rules for Derived Classes class A { public: A ( ) {cout<< A::A()<

class C : public A { public: C (int c): A(c){ A(c) cout<

Derived 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); //... } 22

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

23 Summary What we have seen so far Inheritance for code reuse reasons Reflects a relationship of Is-A Inheritance means that the derived inherits its base class characteristics Class Person name The derived class can add to this GetName() characteristics of its own Class Worker salary CalculateSal() 24 Summary cont. 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 Worker w; w.GetName(); 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 access keyword has been introduced 25 7. Polymorphic Inheritance Animal 26 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 m_salary v. CalcSalary() Class SalesPerson m_sales v. CalcSalary() Class Executive m_performance v. CalcSalary() Class Administrative v. CalcSalary() 27 Example Employee* employees[100];

Executive Administrative Executive Administrative Sales Person We want each element in the container to call its own CalcSalary() method as a function of the real object Employee Employee::CalcSalary() SalesPerson Executive SalesPerson::CalcSalary() Executive::CalcSalary()

Administrative Administrative::CalcSalary() 28 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 Executive exec; Employee* emp = &exec; Can be dangerous in some cases

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

Virtual Functions Definition: Member function prefaced by the virtual specifier. Compiler generates the code that will select the appropriate function at runtime virtual 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 (); }; 31 Examples Employee *p0 = new Employee; Employee *p1 = new SalariedEmployee; p0->CalcSalary(); // calls Employee::CalcSalary()

p1->CalcSalary(); // calls SalariedEmployee::CalcSalary() 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 32 Virtual Functions 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";}; };

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; }; 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(); Output: B:x B:y B:x B:y A:x B:y A:y 33 Combinations of virtual and nonvirtual 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(); 34 Combinations of virtual and nonvirtual 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();

35 Common Interface Virtual 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; }; 36 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); } }; 37 Example (cont.) int main () { Rectangle rect; Triangle trgl; Polygon * ppoly1 = ▭ Polygon * ppoly2 = &trgl; ppoly1->set_values (4,5);

ppoly2->set_values (4,5); cout << ppoly1->area() << endl; // 20 cout << ppoly2->area() << endl; // 10 return 0; } 38 Virtual Destructors Destructor preceded by the virtual specifier Correct destructor must be called It is recommended that any class containing virtual functions should also have a virtual destructor class Item { class BookItem : public Item{ public: public:

virtual ~Item(); //... virtual ~BookItem(); private: char * title; }; }; BookItem needs a separate destructor to deallocate the storage for title 39 Pure Virtual The Employee can define this method at the base class as pure virtual : virtual int Employee::CalcSalary() = 0; Meaning, 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 40 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); } }; 41 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; }; A is an Abstract Base Class Declares pure virtual functions (=0) Derived classes override pure virtual methods B overrides x(), C overrides y() Cant 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

42 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 43 Dynamic Binding - Implementation Employee* employees[100];

Executive Administrative Executive Administrative Sales Person Executive Virtual Table Sales Person Virtual Table Executive::CalcSalary() SalesPerson::CalcSalary() 44 Summary: Tips on Polymorphism Push common code and variables up into base classes Use public inheritance for polymorphism Polymorphism depends on dynamic typing

Use a base-class pointer or reference if you want polymorphism Use virtual member functions for dynamic overriding Use private inheritance only for encapsulation Use abstract base classes to declare interfaces Even though you dont have to, label each virtual method (and pure virtual method) in derived classes 45 8. Multiple Inheritance 46 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 47 Construction and Destruction 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? Class Employee m_salary v. CalcSalary()

Class SalesPerson m_sales v. CalcSalary() Class Executive m_performance v. CalcSalary() Class Administrative v. CalcSalary() 48 Multiple Inheritance 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? Class Student

Class Employee m_salary v. CalcSalary() v. M() Class Metargel v. CalcSalary() v. M() Class Person Class SalesPerson m_sales v. CalcSalary() Class Executive m_performance v. CalcSalary() Class Administrative v. CalcSalary()

49 Syntax class Metargel : public Student, public Employee { // } Teaching Assistant maintains the attributes and the methods associated with both base classes Student, and Employee 50 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 51

Problems with Multiple Inheritance 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 A common misuse of multiple inheritance is using it as composition rather than specialization (is-a): The following is incorrect: incorrect class car: public Engine, public Transmission, public Wheels 52 Name Ambiguity Solution 1:

Use a fully qualified function name: Metargel * myMetargel = new Metargel; cout << The TeachingAssistant is << myMetargel -> Employee::get_id() << \n; 53 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(); } 54 Virtual Inheritance - Motivation What if class student and class Employee both inherit from Person? How can this be dealt with? Class Person m_name Class Person m_name Class Student Class Employee m_salary v. CalcSalary()

v. M() Class Metargel v. CalcSalary() v. M() Class SalesPerson m_sales v. CalcSalary() Class Executive m_performance v. CalcSalary() Class Administrative v. CalcSalary() 55 Replicated Base Classes The same class can not be directly inherited more than once Base 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 56 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 class class class

A { }; B: public A { }; C: public A { }; /* Derives from A but it isnt shared!*/ D: public B, public C { }; This gives us the following situation: A B A* a; B* b; C* c; D* d; b = d; // ok A A B C

c = d; // ok a = b; // ok D a = c; // ok a = d; //error ambiguous A C D 57 Virtual Inheritance Single instance within layout Class Person Class Student Class Employee

m_salary v. CalcSalary() v. M() Class Metargel v. CalcSalary() v. M() Class SalesPerson m_sales v. CalcSalary() Class Executive m_performance v. CalcSalary() Class Administrative v. CalcSalary() 58 Virtual Base Classes

To merge any common base classes into one single copy the inheritance should be written as virtual: virtual class Employee: virtual public Person {..} class Student: virtual public Person {..} class TeachingAssistant : public Student, public Employee {..} 59 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

A B C D A B C D 60 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 61 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 Recommended to use as many as possible abstract classes, classes and not multiple inheritance Make sure this really models your problem domain well 62

Recently Viewed Presentations

  • IEEE P802.11 WG Treasury Report

    IEEE P802.11 WG Treasury Report

    March 20, 2005 Closing Plenary Report Nanci Vogtli Agenda Recent Activities Press releases: formation of 802.11w was announced Press inquires and interviews: NY Times CNET CRN Calendar of Events template completed and ready to post to the website for testing...
  • Peritonitis - Semmelweis Egyetem

    Peritonitis - Semmelweis Egyetem

    Peritonitis Peritonitis Intra-abdominal infections Two major clinical manifestations Early or diffuse infection results in localised or generalised peritonitis Bacterial peritonitis is classified as primary or secondary Late and localised infections produces an intra-abdominal abscess Pathophysiology depend on competing factors of...
  • Dynasties Rule! - Typepad

    Dynasties Rule! - Typepad

    Dynasty Focus Zhou (Jou) Qin (pronounced Chin) Tang Yuan Ming Qing (pronounced Ching) Commemorative Marker Your task is to create a commemorative marker that highlights the importance of your dynasty. The commemorative marker should honor the memory of your dynasty.
  • CO-1 Instructors Workshop #1. Welcome

    CO-1 Instructors Workshop #1. Welcome

    Inverts traditional teaching methods using online instruction outside the classroom and moving traditional "homework" into the classroom. Compliments of Knewton - Education Technology Company. NTTC - Dallas 2014. Next: Les gives a brief description for VA's beginning of immersion
  • BONE TUMORS - JUdoctors

    BONE TUMORS - JUdoctors

    Most bone tumors occur in 1st few decades of life, with few tumors exceptionally affect adults. Mostly originate in long bones of extremities. One of the exceptions: Chondrosarcomastend to develop during mid- to late adulthood and involve the trunk, limb...
  • Images &amp; Tables - DePaul University

    Images & Tables - DePaul University

    Images & Tables Image file formats Three graphic file types are supported by today's browsers: GIF - Graphic Interchange Format JPEG - Joint Photographic Experts Group PNG - Portable Network Graphics GIF GIF files are best used for images that...
  • Quarter Payments - actweb.acttax.com

    Quarter Payments - actweb.acttax.com

    Reversal with "QP" Deposit. If you choose to set the Q on the Tax Detail screen manually and set the client preference to 'N' all accounts with a Q will be divided regardless of qualifications met when BMI 1228 runs...
  • Rail Security and the passenger interface Prof. Dr.

    Rail Security and the passenger interface Prof. Dr.

    Rail Security. REAL TIME TARGETED INFORMATION (AUTOMATIC/SEMIAUTOMATIC FLOWS) (Customer Operations Control System) (CRM system) (CMS system) Monitor the customer experience and switch on alerts in case of disruptions