Presentation is loading. Please wait.

Presentation is loading. Please wait.

Slide 1 Inheritance: Part I. Slide 2 Structuring ‘classes’ class Employee { string firstName; string familyName; … } class Manager { Employee e; list.

Similar presentations


Presentation on theme: "Slide 1 Inheritance: Part I. Slide 2 Structuring ‘classes’ class Employee { string firstName; string familyName; … } class Manager { Employee e; list."— Presentation transcript:

1 Slide 1 Inheritance: Part I

2 Slide 2 Structuring ‘classes’ class Employee { string firstName; string familyName; … } class Manager { Employee e; list group; … } class X { … } class Y { X x; … } l Y has a X as a component, l but a y of Y is NOT a x of X l a ‘Manager’ is an ‘Employee’

3 Slide 3 Relationships Between Classes n Composition (class in class) n “has-a” relationship n Object contains one or more objects of other classes as members n Example: A car has a wheel n Inheritance (derived class) n “is-a” relationship n Derived class object can be treated as base class object n Example: A car is a vehicle COMP1523

4 Slide 4 Example COMP1524

5 Slide 5 Another Example COMP1525

6 Slide 6 Derived Class class Employee { string firstName; string familyName; … } class Manager : public Employee { list group; … } l a ‘Manager’ is a ‘Employee’! l a derived class object can be treated as a base class object.

7 Slide 7 (Public) Inheritance * Base class (super-class), derived class (sub-class) n Derived class object is a specialization and is a ‘superset’ of the data of its base class object * Derived class inherits all members of base class (and members of all its ancestor classes) n Public members of the base class  Inherited, so accessible n Private members of the base class  Not accessible directly: comes as a surprise, but ‘privacy’ would have been rendered meaningless if allowed by deriving a new class  Accessed through public member functions * Friend functions are not inherited COMP1527

8 Slide 8 class Employee { public: string fullName(); private: string firstName; string familyName; … } class Manager : public Employee { public: void print() const; private: list group; … } void Manager::print() const { cout << fullName() << endl; } Void Manager::print() const { cout << firstName << familyName << endl; } No, because of privacy! Yes.

9 Slide 9 Class-in-Class vs. Inheritance * A class declares another class as its data member, hence creating an object within another object * Inheritance and class-in-class are two quite different things and concepts in implementation and OOP. * Inheritance has a "is-a" relationship between derived class and base class, while class-in-class is a "has-a" relationship * Generally, we can decide whether to use inheritance or class-in-class by common sense. If we can find some common relationship between two or more things, we should use inheritance. n For example, Citizen and Student with Citizen as the base class. It makes no sense to implement a Citizen class inside a Student class. * In class-in-class, the inner class is a standalone object. Thus, the inner class and the outer class do not share the powerful features in inheritance (such as polymorphism and dynamic binding). COMP1529

10 Slide 10 ‘protected’ members  the private data members in the base class cannot be accessed by its derived classes  the protected data members in the base class can be accessed by its derived classes, but not other non- derived classes COMP15210 The ‘protected’ is the ‘shared privacy’ between base and derived classes !

11 Slide 11 class Employee { protected: string firstName; string familyName; … } class Manager : public Employee { public: void print() const; private: list group; … } void Manager::print() const { cout << firstName << familyName << endl; }

12 Slide 12 Protection control: public, protected, private  Intermediate level of protection between public and private n For both data members and function members n Want the derived class to directly access members while forbid other classes to access them directly  protected members in the Base class are accessible to n Base class members n Base class friends n Derived class members n Derived class friends COMP15212

13 Slide 13 Pros/Cons of ‘ Protected ’ * Advantages n Derived class can modify values directly n Avoid set/get method call overhead  Slight increase in performance * Disadvantages n No validity checking: Derived class can assign illegal value to protected members n Implementation-dependent on the base class  Derived class functions are usually very likely dependent on base class implementation  Using protected access, base class implementation changes may result in derived class modifications, e.g., a change to a different printing format in the base class may cause the printing function to be changed in the derived class  This leads to fragile (brittle) software COMP15213

14 Slide 14 Constructors of Derived Classes COMP15214 class Y : public X { public Y::Y(); }; Y::Y() : X() { … };

15 Slide 15 COMP15215 class Employee { protected: Employee(); string firstName; string familyName; … } class Manager : public Employee { private: list group; int level; } Employee e; Manager m; // use default ‘employee’ constructor If no constructor, use the default base constructor.

16 Slide 16 COMP15216 class Employee { public: Employee(); private: string firstName; string familyName; … } class Manager : public Employee { public: Manager(); private: list group; int level; } Manager::Manager() : Employee() { level = … group = … } Employee e; Manager m; // use ‘manager’s constructor

17 Slide 17 COMP15217 class Employee { private: string firstName; string familyName; … } class Manager : public Employee { private: list group; int level; } Employee::Employee(const string& first, const string& family) { } Manager::Manager(const string& first, const string& family, int l) : Employee(n), level(l) { … } If a base class has a constructor with arguments, then it is compulsary for the derived class to have a constructor and pass the arguments to the base class constructor. Passing ‘Arguments’ between ‘Base’ and ‘Derived’ Class Constructors

18 Slide 18 Constructors of Derived Classes and Order of Construction COMP15218 * Class objects are constructed from the bottom up: n First the base, n Then the members, n And then the derivated class itself. * Members and bases are constructed in order of declaration. * When a program creates a derived-class object: 1. The derived-class constructor immediately calls the base-class constructor 2. The base-class constructor’s body (i.e., within {} ) executes 3. Then the derived class’s member initializer list execute 4. Finally the derived-class constructor’s body executes * This process cascades up the hierarchy if the hierarchy contains more than two levels in a recursive manner

19 Slide 19 Destructor COMP15219 class Y : public X { public Y::~Y(); }; Y::~Y() { … };

20 Slide 20 Order of Destruction * Class objects are destroyed in the opposite order of the construction: n First the derived class itself, n Then the members, n And then the base. * Members and bases are destroyed in the reverse order of declaration. * Example on order of construction and destruction n CommissionEmployee4.h, CommissionEmployee4.cpp, BasePlusCommissionEmployee4.h, BasePlusCommissionEmployee4.cpp, order.cpp COMP15220

21 Slide 21 Over-riding (not over-loading): Reusing Operations of Base Classes * Derived class may extend or replace base class function of the same name n Therefore, it hides (or overrides) the base-class version of the function n Still possible to call the base class function with scope resolution operator COMP15221 class X { f(); }; Class Y : public X {}; void Y::f() { … X::f(); … }

22 Slide 22 COMP15222 class X { public: void print(){cout << "base\n";} }; class Y : public X { public: void print( int i ){ cout << i << " Derived\n";} void print( char ch ){ cout << ch << " Derived\n";} }; int main(){ Y y; y.print( 2 ); // print 2 Derived y.print(‘y'); // print y Derived // y.print(); Not O.K.: no matching function for Y::print() }

23 Slide 23 Remarks * Beware of ‘infinite recursion’ in function over-riding, if the scope :: operator is not prefixed with the name of the base class when referencing the base class’s member function causes infinite recursion * which version of the function to call or function resolution is a major issue!  static or dynamic binding! COMP15223

24 Slide 24 Example * CommissionEmployee n First name, last name, SSN (Social Security Number, i.e., ID), commission rate, gross sale amount * BasePlusCommissionEmployee n CommissionEmployee: First name, last name, SSN, commission rate, gross sale amount n And also base salary  Class BasePlusCommissionEmployee n Much of the code is similar to CommissionEmployee n Additions  private data member baseSalary  Methods setBaseSalary and getBaseSalary COMP15224

25 Slide 25 * Derived from class CommissionEmployee n Is a CommissionEmployee n Inherits all public members n Use base-class initializer syntax to initialize base-class data member * Has data member baseSalary * Base class implementation CommissionEmployee1.h, CommissionEmployee1.cpp * Derived class implementation BasePlueCommissionEmployee1.h, BasePlusCommissionEmployee1.cpp  Compilation error because derived class cannot directly access private members of CommissionEmployee class in print() and earnings() COMP15225

26 Slide 26 tester2.cpp Sample Output COMP15226 Employee information obtained by get functions: First name is Bob Last name is Lewis Social security number is 333-33-3333 Gross sales is 5000.00 Commission rate is 0.04 Base salary is 300.00 Updated employee information output by print function: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: 5000.00 commission rate: 0.04 base salary: 1000.00 Employee's earnings: $1200.00

27 Slide 27 Summary * ‘is-a’ relationship n Different from ‘has-a’ or ‘uses-a’, or … by class-in-class * Public inheritance n Public n Private * ‘protected’ * Constructors/destructors * Redefinition (over-riding)  which version for which object??? * Not inherited: n Friend functions COMP15227

28 Slide 28 order.cpp Sample Output (1/2) COMP15228 CommissionEmployee constructor: commission employee: Bob Lewis social security number: 333-33-3333 gross sales: 5000.00 commission rate: 0.04 CommissionEmployee destructor: commission employee: Bob Lewis social security number: 333-33-3333 gross sales: 5000.00 commission rate: 0.04 CommissionEmployee constructor: base-salaried commission employee: Lisa Jones social security number: 555-55-5555 gross sales: 2000.00 commission rate: 0.06 CommissionEmployee constructor called for object in block; destructor called immediately as execution leaves scope Base-class CommissionEmployee constructor executes first when instantiating derived-class BasePlusCommissionEmployee object BasePlusCommissionEmployee constructor: base-salaried commission employee: Lisa Jones social security number: 555-55-5555 gross sales: 2000.00 commission rate: 0.06 base salary: 800.00 CommissionEmployee constructor: commission employee: Mark Sands social security number: 888-88-8888 gross sales: 8000.00 commission rate: 0.15 Derived-class BasePlusCommissionEmployee constructor body executes after base-class CommissionEmployee’s constructor finishes execution Base-class CommissionEmployee constructor executes first when instantiating derived-class BasePlusCommissionEmployee object

29 Slide 29 order.cpp Sample Output (2/2) COMP15229 BasePlusCommissionEmployee constructor: base-salaried commission employee: Mark Sands social security number: 888-88-8888 gross sales: 8000.00 commission rate: 0.15 base salary: 2000.00 BasePlusCommissionEmployee destructor: base-salaried commission employee: Mark Sands social security number: 888-88-8888 gross sales: 8000.00 commission rate: 0.15 base salary: 2000.00 CommissionEmployee destructor: commission employee: Mark Sands social security number: 888-88-8888 gross sales: 8000.00 commission rate: 0.15 Derived-class BasePlusCommissionEmployee constructor body executes after base-class CommissionEmployee’s constructor finishes execution Destructors for BasePlusCommissionEmployee object called in reverse order of constructors BasePlusCommissionEmployee destructor: base-salaried commission employee: Lisa Jones social security number: 555-55-5555 gross sales: 2000.00 commission rate: 0.06 base salary: 800.00 CommissionEmployee destructor: commission employee: Lisa Jones social security number: 555-55-5555 gross sales: 2000.00 commission rate: 0.06 Destructors for BasePlusCommissionEmployee object called in reverse order of constructors

30 Slide 30 Inheritance: Part II

31 Slide 31 A More General Derived Class COMP15231 class Y : public X {…} class Y : protected X {…}; class Y : private X {…};

32 Slide 32 Increasing Access Restrictions  public inheritance (written as class derived: public base) n Base class public members  derived class public members n Base class protected members  derived class protected members n All classes can directly access the public members n Only the derived classes can directly access the protected members  protected inheritance (written as class derived: protected base) n Base class public and protected members  derived class protected members n Classes in the inheritance hierarchy can still access the members (because they are protected members), but not for other classes  private inheritance (written as class derived: private base) n Base class public and protected members  derived class private members n Classes in the downstream inheritance hierarchy can no longer access the members (and neither can all the other classes) COMP15232 public protected public protected public protected public protected private Base class Derived class public protected private

33 Slide 33 Types of Inheritance and Member Access COMP15233

34 Slide 34 COMP152 34 int main(){ Base b; public_derived pub_d; protected_derived prot_d; private_derived priv_d; b.f(); // b.g(); error: 'void Base::g()' is protected pub_d.f(); // pub_d.g(); error: 'void Base::g()' is protected // prot_d.f(); error: 'void Base::f()' is inaccessible // prot_d.g(); error: 'Base' is not an accessible base of 'protected_derived' // priv_d.f(); similar error as above // priv_d.g(); similar error as above return 1; } class Base { public: void f() {cout << "Base::f()" << endl;} protected: void g() {cout << "Base::g()" << endl;} }; class public_derived: public Base { }; class protected_derived: protected Base { }; class private_derived: private Base { };

35 Slide 35 Class hierarchy * Direct base class n Inherited explicitly (one level up hierarchy) n E.g., driver licenses and license * Indirect base class n Inherited two or more levels up hierarchy n E.g., car license and license * Single inheritance n Inherits from one base class n E.g., the above license example * Multiple inheritance n Inherits from multiple base classes n Base classes possibly unrelated n E.g., A “university student” is both a “hard-working person” and a “clever person” COMP15235

36 Slide 36 Multiple Inheritance * When a derived class inherits members from two or more base classes n Provide comma-separated list of base classes after the colon following the derived class name * Can cause ambiguity problems n Should be used only by experienced programmers n Newer languages do not allow multiple inheritance n A common issue occurs if more than one base class contains a member with the same name  Solved by using the scope resolution operator (by the user!) COMP15236

37 Slide 37 Multiple Inheritence (Cont.) * Should be used when an “is a” relationship exists between a new type and two or more existing types n i.e. type A “is a” type B and type A “is a” type C * Can introduce complexity into a system n Great care is required in the design of a system to use multiple inheritance properly Should not be used when single inheritance and/or composition will do the job COMP15237

38 Slide 38 Example: Base1.h, Base2.h, Derived.h, Derived.cpp, multiple.cpp COMP15238

39 Slide 39 Base1.h COMP15239 class Base1 { public: Base1( int parameterValue ) { value = parameterValue; } int getData() const { return value; } protected: int value; }; Class Base1 declares member function getData

40 Slide 40 Base2.h COMP15240 class Base2 { public: Base2( char characterData ) { letter = characterData; } char getData() const { return letter; } protected: char letter; }; Class Base2 also declares member function getData, same name as Base1

41 Slide 41 Derived.h  Class Derived inherits from both class Base1 and class Base2 through multiple inheritance COMP15241 #include "Base1.h" #include "Base2.h" class Derived : public Base1, public Base2 { friend ostream& operator<<( ostream&, const Derived&); public: Derived(int, char, double); double getReal() const; private: double real; };

42 Slide 42 multiple.cpp Sample Output * Note the use of base-class pointer pointing to a derived-class objects n Invoking the member function of the derived object COMP15242 Object base1 contains integer 10 Object base2 contains character Z Object derived contains: Integer: 7 Character: A Real number: 3.5 Data members of Derived can be accessed individually: Integer: 7 Character: A Real number: 3.5 Derived can be treated as an object of either base class: base1Ptr->getData() yields 7 base2Ptr->getData() yields A

43 Slide 43 Software Engineering: Customizing Existing Software with Inheritance n Inheriting from existing classes  Can include additional members  Can redefine base-class members  No direct access to base class’s source code l Only links to object code n Good for those independent software vendors (ISVs)  Develop proprietary code for sale/license l Available in object-code format  Users derive new classes l Without accessing ISV proprietary source code COMP15243


Download ppt "Slide 1 Inheritance: Part I. Slide 2 Structuring ‘classes’ class Employee { string firstName; string familyName; … } class Manager { Employee e; list."

Similar presentations


Ads by Google