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

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Advertisements

Copyright 2006 Oxford Consulting, Ltd1 February C++ Inheritance Data Abstraction and Abstract Data Types Abstract Data Type Encapsulated data.
Inheritance In C++  Inheritance is a mechanism for building class types from other class types defining new class types to be a –specialization –augmentation.
Inheritance Inheritance Reserved word protected Reserved word super
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Inheritance, Polymorphism, and Virtual Functions
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
VIRTUAL FUNCTIONS AND DYNAMIC POLYMORPHISM. *Polymorphism refers to the property by which objects belonging to different classes are able to respond to.
Chapter 12: Adding Functionality to Your Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Dr. Ahmad R. Hadaegh A.R. Hadaegh California State University San Marcos (CSUSM) Page 1 Virtual Functions Polymorphism Abstract base classes.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Class Members Class Definition – class Name – { – public: » constructor(s) » destructor » function members » data members – protected: » function members.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Copyright 2008 Oxford Consulting, Ltd 1 October C++ Classes Enhanced Structures C  struct only permitted to have data members  Functions to.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Inheritance  Virtual Function.
Object Oriented Programming
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
CS212: Object Oriented Analysis and Design Lecture 16: Runtime Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
Overview of C++ Polymorphism
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Object-Oriented Programming: Inheritance and Polymorphism.
Copyright © 2012 Pearson Education, Inc. Chapter 10 Advanced Topics.
 2006 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
7. Inheritance and Polymorphism
Object-Oriented Programming
Inheritance, Polymorphism, and Virtual Functions
Inheritance and Run time Polymorphism
CS212: Object Oriented Analysis and Design
Polymorphism & Virtual Functions
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Polymorphism Lec
Virtual Functions Department of CSE, BUET Chapter 10.
Inheritance, Polymorphism, and Virtual Functions
Polymorphism Polymorphism
Java – Inheritance.
CISC/CMPE320 - Prof. McLeod
VIRTUAL FUNCTIONS RITIKA SHARMA.
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Computer Science II for Majors
Presentation 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 Based Auto 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 BicyclesAutos 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 Inheritance Vehicle Land Based Automobile Motor Boat AutoBoat Water 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

- 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

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

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

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

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

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

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

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

Copyright 2006 Oxford Consulting, Ltd 1 February 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

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

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

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

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

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)

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

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.

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.

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.

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

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

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

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 }

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

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

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.

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 stem seeds skin this

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 stem skin fp -> stem ((Apple *) fp) -> stem

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

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

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

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

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

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

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

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

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 }

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

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

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

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;

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

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

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 Gives Uniform Function Call Interface Base Derived1 Derived2 Derived3 …….. 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

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

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

Polymorphism 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

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

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

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

Polymorphism A B : public A C : public B D : public C E : public D 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 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

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

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

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

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

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

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 ( );

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

Polymorphism Virtual Functions 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

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

Polymorphism Virtual Base Classes – Parent classes may have a common base class Fruit Peach Fruit PlumPeach Nectarine 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

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

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

Polymorphism Virtual Base Classes - Implementation B 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 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

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