Presentation is loading. Please wait.

Presentation is loading. Please wait.

- 1 - C++ Inheritance Data Abstraction and Abstract Data Types – Abstract Data Type Encapsulated data type Accessible only through interface Properties.

Similar presentations


Presentation on theme: "- 1 - C++ Inheritance Data Abstraction and Abstract Data Types – Abstract Data Type Encapsulated data type Accessible only through interface Properties."— Presentation transcript:

1 - 1 - C++ Inheritance Data Abstraction and Abstract Data Types – Abstract Data Type Encapsulated data type Accessible only through interface Properties – Defined by the interface not by the Internal structure or – Implementation – Data Abstraction Effective technique for extending predefined type system When one has a single clearly defined concept

2 - 2 - C++ Inheritance Inheritance – In C++ Inheritance is a mechanism for – Building class types from other class types – Defining new class types to be a …. » Specialization » Augmentation – of existing types

3 - 3 - C++ Inheritance Inheritance – Inheritance is a familiar concept…. Inherit – From parents – In Biology » Kingdom » Phylum » Class » Order » Family » Genus » Species Vehicles Land Based Auto Bicycle

4 - 4 - C++ Inheritance Inheritance – Subgroupings with respect to a parent are called  Subclass  Derived Class  Children – The subclass Inherits  Characteristics  Properties  Capabilities – The subclass can modify or extend inherited abilities

5 - 5 - C++ Inheritance Inheritance Vehicle Class Land Based BicyclesAutos myVehicle myLandBased myAuto myBicycle Instance

6 - 6 - C++ Inheritance Inheritance – Instance hierarchy follows the class hierarchy Single Inheritance – Each object has a single parent » Class » Instance Multiple Inheritance – Classes inherit from multiple base classes – Defines a relationship » Between several (independent) class types

7 - 7 - C++ Inheritance Multiple Inheritance Vehicle Land Based Automobile Motor Boat AutoBoat Water Based Multiple Parents Common Ancestor

8 - 8 - C++ Inheritance Multiple Inheritance – Can also have inheritance without common parent…. Motor Boat Inherits from 2 independent classes  Vehicle  Taxable Item

9 - 9 - C++ Inheritance Virtual Inheritance – The derived class AutoBoat…… Inherits Attributes and Properties – From » Automobile » Motor Boat » Vehicle Vehicle Land Based Automobile Motor Boat AutoBoat Water Based

10 - 10 - C++ Inheritance Inheritance - Derivation Hierarchy – The class vehicle is an abstraction….. It represents an encapsulation of common – Properties – Attributes – Its sole purpose Define a class from which to derive other classes…... – It encapsulates common » Data members » Function members – Called Abstract base class Abstract super class

11 - 11 - C++ Inheritance Inheritance - Abstract Super Class  Key element in the derivation hierarchy  Ensures that all derived classes Share a common set of class members inherited from abstract super class  Provides a common public interface to the class hierarchy

12 - 12 - C++ Inheritance C++ Class Derivation – Any class can serve as a base class... Thus a derived class can also be a base class. Worth spending time at the outset of a design to develop sound definition. – syntax class DerivedClassName : specification BaseClassName – DerivedClassName - the class being derived – specification - specifies access to the base class – members » Public » Protected » Private » private by default

13 - 13 - C++ Inheritance C++ Class Derivation – class A be derived from base class B or C B public C private 1.class A : public B 2.class A : private C

14 - 14 - C++ Inheritance C++ Class Derivation – class A : public B In class A – The inherited public members of B – Appear as public members of A If myValue is a public data member of B – myValue can be accessed publicly through instances of A A d; d.myValue;// ok

15 - 15 - C++ Inheritance C++ Class Derivation – class A : private B In class A – The inherited public members of B – Appear as private members of A if myValue is a public data member of B – myValue cannot be accessed publicly and directly through – instances of A A d; d.myValue;// compile error Function members of A can still access public members of B as public

16 - 16 - C++ Inheritance C++ Class Derivation - Public Derivation – class A { } – class C : public B { } – Objects are created from the inside out and... A Part B Part C Part C Object B Part C Part Constructors A :: A B :: B C :: C

17 Copyright 2006 Oxford Consulting, Ltd 1 February 2006 - 17 - C++ Inheritance C++ Class Derivation - Public Derivation – class A { } – class C : public B { } – Objects are destructed from the outside in: C Part B Part A Part C Object B Part A Part Destructors C :: C B :: B A :: A

18 - 18 - C++ Inheritance C++ Class Derivation - Constructors and Destructors – Constructors and destructors are not inherited…. Initialization and Deinitialization – Implemented as series of constructor calls » Base » Derived classes Different constructors and destructors collaborate to complete the tasks

19 - 19 - C++ Inheritance C++ Class Derivation - Constructors and Destructors – When derived object instantiated, memory allocated for Base object Added parts – Initialization then occurs in two stages…... Base class constructors invoked to initialize the base objects Derived class constructor invoked to complete the task – Derived class constructor Specifies base class constructor in the initialization list – If no constructor in the base class use the default – If the base class is derived the procedure applied recursively

20 - 20 - C++ Inheritance C++ Class Derivation - Constructors and Destructors – Inherited Member Initialization If the base class has only a default constructor – Initialize the member values in body of the derived class – constructor If the base class has constructor with arguments – The initialization list is used to pass arguments to the base – class constructors syntax – DerivedClass ( derivedClass args ) : BaseClass ( baseClass args ) – { » DerivedClass constructor body – }

21 - 21 - C++ Inheritance C++ Class Derivation - Member Access Under Derivation – C1 Defines the base class members – C2 Over rides c ( ) Defines e ( ) – C3 Over rides d ( ) – If C3 accesses aselfc2 c1 bselfc2 c1 cselfc2 dself eself c2 C1 C2 C3 data member a function member b() function member c() function member d() function member c() function member e() function member d()

22 - 22 - C++ Inheritance C++ Class Derivation - Member Access Under Derivation – 1.Access to inherited members by derived members and friends FIs independent of the base class designation in the derivation specification FAccess is allowed to all non-private inherited members FAccess is not allowed to private members (of the parent)

23 - 23 - C++ Inheritance C++ Class Derivation - Member Access Under Derivation – 2.Access to inherited members by functions outside the derivation hierarchy is driven by the base class designation in the derivation specification. If the specification is – public » public members remain public » protected members remain protected – protected » inherited non-private members accessible as protected – private » no outside access

24 - 24 - C++ Inheritance C++ Class Derivation - Member Access Under Derivation – 3.Over riding - An inherited member that is normally visible can be masked Define a derived class member with the same name This is not good practice with non-virtual functions.

25 - 25 - C++ Inheritance C++ Class Derivation – Derivation Guidelines 1. Derivation is not always the best way to extend the system. 2.Use public derivation » When the derived object is a kind of (AKO) base class 3.Use private derivation » When the derived object is not a kind of base class but » derivation makes code development easier. 4.Use protected derivation » When private derivation is suitable but member access » from further derived classes is desirable.

26 - 26 - C++ Inheritance C++ Class Derivation – Base Class Member Specification Guidelines Classes designed as base classes are the same as ordinary classes Declare as protected – Function and data members Intended to be inherited but not – intended to be public. – Declare as virtual – Function members intended to be implemented by derived – classes.

27 - 27 - C++ Inheritance C++ Class Derivation - Member Layout – Single Inheritance struct A { – int a1; – void af ( ); }; struct B : A { – int b1; – void bf1 ( ); }; B :: b1 A*, B* -> A :: a1 A* -> A :: a1

28 - 28 - C++ Inheritance C++ Class Derivation - Member Layout – Multiple Inheritance struct C { – int c1; – void cf ( ); }; struct D : A, C { – int d1; – void df1 ( ); }; C :: c1 C* -> D :: d1 A*, D* -> C :: c1 C* -> A :: a1

29 - 29 - C++ Inheritance C++ Class Derivation - Member Layout – Virtual Inheritance struct E : virtual A { – int e1; – void ef ( ); }; E :: vbptr E :: e1 E* -> Shared Members

30 - 30 - C++ Inheritance C++ Class Derivation - Private Derivation – If the derivation specification is changed to….. class BaseClass { public: – BaseClass() {baseValue = 20;} – int baseValue; }; class DerivedClass : private BaseClass main (void) { – DerivedClass child; – child.baseValue = 30;// compile error }

31 - 31 - C++ Inheritance C++ Class Derivation - Private Derivation – Exemptions C++ provides a means through which individual members can be made exempt from a private derivation – syntax – Data members » BaseClass :: data member – Function members » BaseClass :: function member

32 - 32 - C++ Inheritance C++ Class Derivation - Protected Derivation – If the derivation specification is changed to Class DerivedClass : protected Base Class  Public and protected members are inherited as protected  Protected members r Act as public within the derivation hierarchy r Act as private from the outside – Class member declared as protected Acts as – public member to » Member functions and friends of derived class – private member to » The rest of the program

33 - 33 - C++ Inheritance C++ Class Derivation - Conversions Under Derivation – There are four predefined conversions between a derived class – and a public base class 1.Derived class object. – Implicitly converted into a public base class object. 2.Derived class reference. – Implicitly converted into a public base class reference. 3.Derived class pointer. – Implicitly converted into a public base class pointer. 4.Pointer to a member of a base class. – Implicitly converted to a pointer to that member in a – publicly derived class.

34 - 34 - C++ Inheritance Apple a, *aPtr = &a;// Derived Class Fruit f, *fPtr = &f; // Base Class 1.a may be used anyplace f is used - contains a base class 2. a may be used as a reference anywhere a reference to f is used - contains a base class. 3.the pointer aPtr may be used anywhere fPtr is used - contains a base class 4.fp -> seeds can be used anywhere ap -> seeds is used - inherited from fruit. C++ Class Derivation - Conversions Under Derivation 1414 stem seeds this 1414 2323 stem seeds skin this

35 - 35 - C++ Inheritance C++ Class Derivation - Conversions Under Derivation Apple a, *aPtr = &a;// Derived Class Fruit f, *fPtr = &f; // Base Class 1.Fruit *fp = new Apple; Implicit conversion - 3 2a.Apple *ap = new Fruit; Error No implicit conversion Skin uninitialized and undefined Stem = 1 but *ap -> stem unitialized 2b.Apple *pa = (Apple *) new Fruit; Legal - Explicit conversion Explicit cast - Legal but dangereous seeds 1414 2323 stem skin fp -> stem ((Apple *) fp) -> stem

36 - 36 - C++ Inheritance Overloaded Functions with Class Type Arguments – Overloaded Function Call Resolution Exact Match – A class argument matches only a formal argument of its own – class – If class B is derived from class A » Overload function f1 » f1 (A a); » f1 (B b); – Then declare an instance of B » B b1; » f1 (b1); // is legal and resolvable

37 - 37 - C++ Inheritance Overloaded Functions with Class Type Arguments – Overloaded Function Call Resolution Standard Conversions - Object Conversion – A derived class Object, Reference, or Pointer is implicitly – converted into a public base class type. – If class B is derived from class A » Overload function f1 » f1 (A a); » f1 (C c);// C is not in the derivation hierarchy – Then declare an instance of B » B b1; » f1 (b1); // is legal and resolvable to the proper // function

38 - 38 - C++ Inheritance Overloaded Functions with Class Type Arguments – Overloaded Function Call Resolution Standard Conversions - void Conversion – A pointer of any class type is implicitly converted into a – pointer of type void. – If class B is derived from class A » Overload function f1 » f1 (C* &c); // C is not in the derivation hierarchy » f1 (void* ); If class B is derived from class A – Then declare an instance of B » B b1; » f1 (&b1); // is legal and resolvable to the proper // function

39 - 39 - C++ Inheritance Overloaded Functions with Class Type Arguments – Overloaded Function Call Resolution Standard Conversions - Programmer Defined Conversion – to: – syntax » operator typeName() { body } » typeName - type to convert to from the class – from: – Use the constructor with a single argument – syntax » X::X ( typeName arg ) { body } » typeName - type to convert from to the class

40 - 40 - C++ Inheritance Copy Constructors and Derivation – If a copy constructor is not supplied for derived class a default copy – constructor is generated Derived default copy constructor copies  Base and member objects » By calling their copy constructors  Data members as a memcopy – If a copy constructor is supplied must specify the desired copy – constructors for  Base and member objects – syntax DerivedClass X (const DerivedClass X& object) : BaseClass (object) object - the object being copied

41 - 41 - C++ Inheritance Over Riding Inherited Members – When a function name is reused or inherited from multiple base – classes - ambiguity results. – Compiler tries to resolve any such conflicts…. Single Path – Use the function in the most immediate scope for which the – signatures are identical Multiple Paths – Use the scope operator or virtual functions

42 - 42 - C++ Inheritance Multiple Base Classes – A derived class can inherit from multiple base classes…. syntax – class DerivedClassName : spec 0 base class 0, spec 1 base class 1,... spec n base class n, » DerivedClassName - the class being derived » Specification - specifies access to the base class members » public » protected » private

43 - 43 - C++ Inheritance Multiple Base Classes – Let: class A be derived from base classes B, C, and D B public C, D private – 1.class A : public B, private C, D – 2.class A : private C, public B, private D – 3.class A : C, D, public B

44 - 44 - C++ Inheritance Multiple Base Classes- Inherited Member Initialization qIf the base class has only a default constructor Initialize the member values in the body of the derived class constructor qA constructor with arguments  The init list used to pass args to the base class constructors  Invocation is left to right, depth first – syntax DerivedClass ( dCl args ) : BC0 (bC0 args), BC1 (bC1 args),...BCn ( bCn args), { – DerivedClass constructor body }

45 Polymorphism Polymorphism – Key issue….. When to implement the action – Compile time » Early Binding » Allows greater execution speed » Achieved through optimized code – Run time » Late Binding » Allows for greater flexibility » Opportunity for abstraction - 45 -

46 Polymorphism Polymorphism – Polymorphism is a major strength of an object centered paradigm – Same general type of action…..  Accomplished in different ways  By different types of objects The underlying software system – Decides how to achieve the action - 46 -

47 Polymorphism Polymorphism and C++ – Early Binding occurs at compile time – Early binding polymorphism » Process of overloading members – Late Binding occurs at runtime – Late binding polymorphism » The code to implement the method is chosen at runtime » Appropriate code chosen sending a message to » the object …. Not to the pointer to the object » Implemented through virtual functions - 47 -

48 Polymorphism Virtual Functions – A virtual function must be declared in a parent class syntax – virtual function » virtual returnType functionName ( args i ) { function body ;} – pure virtual function » virtual returnType functionName ( args i ) = 0; - 48 -

49 Polymorphism Virtual Functions – Declaration A function name is preceded by the keyword virtual qFunction name can only be used once in the parent class qCannot overload virtual functions qOnly class member functions can be declared virtual A function is virtual…..  If it is declared virtual  There is a base class function with the same signature – declared virtual Any or all class member functions (except constructors) can be declared virtual - 49 -

50 Polymorphism Virtual Functions – Implementation  The body of the virtual function must be supplied in the parent class unless declared to be a pure virtual function  A derived class can override the definition by providing its own implementation » If the re-declaration does not match exactly…... » The function not considered virtual for that class  A virtual function still permitted in a subsequently derived class - 50 -

51 Polymorphism Virtual Functions – Such a capability permits multiple functions to be called through a – common interface. – Can be overridden by explicit qualification with the scope operator. - 51 - Gives Uniform Function Call Interface Base Derived1 Derived2 Derived3 …….. Derivedn Public Interface

52 Polymorphism Virtual Functions – When function in a class is declared virtual Keyword virtual tells compiler  Don’t perform early binding  Install mechanisms to perform late binding Compiler responds by creating  Table of function pointers  Installing a data member to the class to point to the table - 52 -

53 Polymorphism Virtual Functions – The compiler created table is called the vtable (vtbl) Contains pointers to all functions declared virtual within the class and derived classes. – Each class gets its own vtable – A data member called the vpointer (vPtr) Usually placed as the first element in object in memory. Initialized to the starting address of the vtable. – The function call through a base class pointer Indexes into the vtable calls the function located at the address. - 53 -

54 Polymorphism - 54 - class A { public: int i; virtual void f ( ); virtual void g( ); }; vptr i &f ( ) &g ( ) vtable[0] vtable[1] class A vtable

55 Polymorphism - 55 - class A { public: int i; virtual void f ( ); }; class B : public A { public: virtual void f ( );// override f( ) virtual void g ( ); // define g () }; class A vtable &f ( ) vtable[0] &f ( ) &g ( ) vtable[0] vtable[1] class B vtable

56 Polymorphism Virtual Functions - vtable  Contains pointers to all virtual functions.  Each class gets its own vtable.  Abstract classes have no vtable.  Vtable size is proportional to the number of virtual functions. - 56 -

57 Polymorphism Virtual Functions - Invocation A virtual function is invoked through a public base class pointer or reference. Runtime Binding  Typically polymorphic binding is done dynamically at runtime  Virtual functions are not inlined Compile Time Binding  Occasionally have compile time polymorphic binding  Invoked through an object of the class type  Invoked using the scope operator  Invoked through a constructor or destructor - 57 -

58 Polymorphism Virtual Functions - Access Protection The access level of a virtual function is determined by  Access level in class of the pointer through which it’s invoked  Not by the class in which it’s defined. - 58 -

59 Polymorphism A B : public A C : public B D : public C E : public D - 59 - Declare a and public virtual function f() public virtual function f() in B protected virtual function f() in C private virtual function f() in D Write: 1. A* a = new B; a-> f(); // f() accessible through *a (as a *B - *a in public area) 2. a = new C; a-> f(); // f() accessible through *a (as a *C - a* in public area) 3. C* c = new D; c-> f(); // f() not accessible through *c (as a *D - c* in protected area)

60 Polymorphism - 60 - Virtual Destructors When a base class pointer is used to refer to a derived class object and the object is deleted….. Only the base class destructor will be invoked leaving behind the derived class parts of the object.

61 Polymorphism Virtual Destructors – syntax virtual ~ class ClassName ( ) { destructor body } Specifying a destructor as virtual ensures all appropriate destructors are invoked. Rule of thumb…..If a class is abstract then declare the destructor as virtual. Don’t declare the destructor if there are no other virtual functions. - 61 -

62 Polymorphism Virtual Destructors – Invocation order…. q The derived type destructor q The destructor for each base class….. – …...Invoked in turn in normal fashion - 62 -

63 Polymorphism Polymorphism and Object Slicing One must exercise caution when treating objects polymorphically – There is a distinct difference between passing objects by value and by reference. When a derived class object is passed by value to a function expecting a base class value…. The derived class portion is sliced off. - 63 -

64 Polymorphism Pure Virtual Functions – ….A virtual function must be defined when it is declared  Abstract base class may be defined that is not intended to be instantiated  If virtual function is declared pure …. an implementation – may still be supplied  Derived class may use implementation - 64 -

65 Polymorphism Pure Virtual Functions – When a function is declared pure….. r There is no address to put into the vtable r The 0 keys the compiler that no instances of this class can be created - 65 -

66 Polymorphism Pure Virtual Functions – Restrictions A class with one or more pure virtual functions. – 1.Can only be used as a base class – 2.Cannot have instances – 3.Cannot be used as  An argument type  Return type  Type for explicit conversion – 4.Can be used as a  Pointer  Reference type A class cannot define a pure virtual destructor - 66 -

67 Polymorphism Pure Virtual Definitions – There may be occasions when it’s desirable to share code with – derived classes but not duplicate in each class. – Can prevent base class instantiation yet provide a definition for a pure – virtual function. syntax – virtual returnType functionName ( argsi ) = 0 { function body } – access » BaseClassName :: functionName ( ); - 67 -

68 Polymorphism Virtual Functions – Rules for Virtual Functions 1. Virtual functions called from within a constructor use the local version. 2.The first class in a derivation hierarchy that declares a virtual function it must provide a definition or it must declare the virtual function to be pure 3.If a definition is provided, the definition serves as the default instance in subsequent derivations 4.If pure, a subsequently derived class must provide a definition - to have instances or inherit the pure virtual function - have no instances - 68 -

69 Polymorphism Virtual Functions - 69 - vf1 1 ( ) vf1 2 ( ) must define vf1 1 ( ) and vf1 2 ( ) vf1 2 ( ) can have instances pvf1 3 ( ) no instances no instances pvf1 3 ( ) = defines pvf1 3 ( ) can have instances Class 1 Class 2 Class 3 Class 4 Class 5

70 Polymorphism Virtual Functions - Access Level – The access level of a virtual function is….. qSpecified in the class where it is defined qNot by initial definition - 70 -

71 Polymorphism Virtual Base Classes – Parent classes may have a common base class - 71 - Fruit Peach Fruit PlumPeach Nectarine Stem Plum

72 Polymorphism Virtual Base Classes – Problem:  Fruit has a stem data member  Peach and plum each inherit a stem member from Fruit  Nectarine inherits a stem member from each  Could resolve using the scope operator – Plum::stem – Peach::stem - 72 -

73 Polymorphism Virtual Base Classes – Solution: Declare Fruit as a virtual base class – Result: Only a single copy of the base class in the derivation hierarchy. Only a single copy of all inherited data members. Subsequent derivations point to shared members. - 73 -

74 Polymorphism Virtual Base Classes - Specification Syntax class DerivedClass : virtual accessSpec BaseClass – DerivedClass - The class being derived – BaseClass- The parent class – Specification- Specify base class member access – public – protected – private The keyword virtual identifies BaseClass as a virtual base class of DerivedClass. - 74 -

75 Polymorphism Virtual Base Classes - Implementation - 75 - B Data Members A Data Members B Data Members Virtual Derivation Non-Virtual Derivation

76 Polymorphism Virtual Base Classes - Access Protection – – When there are multiple paths from a common root … – ….the most public path dominates. - 76 - Fruit PlumPeach Nectarine virtual public virtual private

77 Polymorphism Virtual Base Classes - Initialization – A virtual base class is initialized by the most derived class. – Initialization Order: 1.Constructors for any virtual base class(es). 2.Constructors for any non-virtual base class. 3.The most derived class must provide initialization values. - 77 -

78 Polymorphism Virtual Base Classes - Initialization Specify class E… class E : public D, public C, public virtual F - 78 - A virtual BC D E F virtual base class


Download ppt "- 1 - C++ Inheritance Data Abstraction and Abstract Data Types – Abstract Data Type Encapsulated data type Accessible only through interface Properties."

Similar presentations


Ads by Google