- 1 - c++ inheritance data abstraction and abstract data types – abstract data type encapsulated...

Post on 26-Dec-2015

228 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

- 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 -

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 -

C++ Inheritance

• Inheritance

– Inheritance is a familiar concept….• Inherit

– From parents– In Biology

» Kingdom» Phylum» Class» Order» Family» Genus» Species

Vehicles

Land BasedAuto Bicycle

- 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 -

C++ Inheritance

• Inheritance

Vehicle

Class

Land Based

Bicycles Autos

myVehicle

myLandBased

myAuto myBicycle

Instance

- 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 -

C++ Inheritance

• Multiple InheritanceVehicleVehicle

Land BasedLand Based

AutomobileAutomobile Motor BoatMotor Boat

AutoBoatAutoBoat

Water BasedWater Based

Multiple Parents Common Ancestor

- 8 -

C++ Inheritance

• Multiple Inheritance

– Can also have inheritance without common parent….

• Motor Boat Inherits from 2 independent classes· Vehicle· Taxable Item Vehicle Vehicle

Water BasedWater Based Luxury ItemLuxury Item

MotorBoatMotorBoat

Taxable ItemTaxable Item

- 9 -

C++ Inheritance

• Virtual Inheritance– The derived class AutoBoat……

• Inherits Attributes and Properties

– From » Automobile» Motor Boat» Vehicle

VehicleVehicle

Land BasedLand Based

AutomobileAutomobile Motor BoatMotor Boat

AutoBoatAutoBoat

Water BasedWater Based

- 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 -

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 -

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 -

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 -

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 -

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 -

C++ Inheritance

• C++ Class Derivation - Public Derivation

– class A { }– class C : public B { }– Objects are created from the inside out and ...

A PartA Part A PartA Part

B PartB Part

C PartC Part

C ObjectC Object

B PartB Part

C PartC Part

Constructors

A :: A

B :: B

C :: C

1 February 2006Copyright 2006 Oxford Consulting, Ltd - 17 -

C++ Inheritance

• C++ Class Derivation - Public Derivation– class A { }– class C : public B { }

– Objects are destructed from the outside in:

C PartC Part C PartC Part

B PartB Part

A PartA Part

C ObjectC Object

B PartB Part

A PartA Part

Destructors

C :: C

B :: B

A :: A

- 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 -

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 -

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 -

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• a self c2 c1• b self c2 c1• c self c2• d self• e self c2

C1

C2

C3

data member afunction member b()function member c()function member d()

function member c()function member e()

function member d()

- 22 -

C++ Inheritance

• C++ Class Derivation - Member Access Under Derivation

– 1. Access to inherited members by derived members and friends

Is independent of the base class designation in the derivation • specification

Access is allowed to all non-private inherited members

Access is not allowed to private members (of the parent)

- 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 -

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 -

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 -

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 -

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 -

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 -

C++ Inheritance

• C++ Class Derivation - Member Layout– Virtual Inheritance

• struct E : virtual A

• {– int e1;– void ef ( );

• };

E :: vbptr

E :: e1

E* ->

SharedMembers

- 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 -

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 -

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

Act as public within the derivation hierarchy 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 -

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 -

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

1

4

stem

seeds

this

1

4

2

3

stem

stem

seeds

skin

this

- 35 -

C++ InheritanceC++ Class Derivation - Conversions Under Derivation

Apple a, *aPtr = &a; // Derived ClassFruit f, *fPtr = &f; // Base Class

1. Fruit *fp = new Apple;Implicit conversion - 3

2a. Apple *ap = new Fruit; Error No implicit conversionSkin uninitialized and undefinedStem = 1 but *ap -> stem unitialized

2b. Apple *pa = (Apple *) new Fruit;Legal - Explicit conversionExplicit cast - Legal but dangereous

seeds

1

4

2

3

stem

stem

skin

fp -> stem

((Apple *) fp) -> stem

- 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 -

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 -

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 -

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 -

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 -

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 -

C++ Inheritance

• Multiple Base Classes

– A derived class can inherit from multiple base classes….

• syntax– class DerivedClassName : spec0 base class0, spec1 base class1, ... specn base

classn,

» DerivedClassName - the class being derived» Specification - specifies access to the base class

members» public» protected» private

- 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 -

C++ Inheritance

• Multiple Base Classes- Inherited Member Initialization If the base class has only a default constructor

• Initialize the member values in the body of the derived class • constructor

A 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• }

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 -

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 -

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 -

Polymorphism

• Virtual Functions

– A virtual function must be declared in a parent class

• syntax– virtual function

» virtual returnType functionName ( argsi ) { function body ;}

– pure virtual function» virtual returnType functionName ( argsi ) = 0;

- 48 -

Polymorphism

• Virtual Functions – Declaration

• A function name is preceded by the keyword virtual Function name can only be used once in the parent class Cannot overload virtual functions Only 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 -

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 -

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 FunctionCall Interface

Base

Derived1Derived2Derived3

……..Derivedn

Public Interface

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 -

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 -

Polymorphism

- 54 -

class A

{

public:

int i;

virtual void f ( );

virtual void g( );

};

vptr

i

&f ( )

&g ( )

vtable[0]

vtable[1]

class A

class Avtable

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 Avtable

&f ( )vtable[0] &f ( )

&g ( )

vtable[0]

vtable[1]

class Bvtable

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 -

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 -

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 -

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)

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.

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 -

Polymorphism

• Virtual Destructors

– Invocation order….

The derived type destructor

The destructor for each base class…..– …...Invoked in turn in normal fashion

- 62 -

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 -

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 -

Polymorphism

• Pure Virtual Functions

– When a function is declared pure…..

There is no address to put into the vtable

The 0 keys the compiler that no instances of this class can be created

- 65 -

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 -

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 -

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 -

Polymorphism

• Virtual Functions

- 69 -

vf11( )vf12( ) must define vf11( ) and vf12( )

vf12( ) can have instances

pvf13( ) no instances

no instances

pvf13( ) = defines pvf13( ) can have instances

Class 1Class 1

Class 2Class 2

Class 3Class 3

Class 4Class 4

Class 5Class 5

Polymorphism

• Virtual Functions - Access Level

– The access level of a virtual function is…..

Specified in the class where it is defined

Not by initial definition

- 70 -

Polymorphism

• Virtual Base Classes– Parent classes may have a common base class

- 71 -

Fruit

Peach

Fruit

PlumPeach

Nectarine

Stem Stem

Plum

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 -

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 -

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 -

Polymorphism

• Virtual Base Classes - Implementation

- 75 -

B Data Members

A Data Members

A Data Members

B Data Members

Virtual Derivation

Non-Virtual Derivation

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

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 -

Polymorphism• Virtual Base Classes - Initialization

• Specify class E…• class E : public D, public C, public virtual F

- 78 -

A

virtualvirtual

B C

D

E

F virtual

virtual base class

top related