Upload
erica-kelly
View
213
Download
0
Tags:
Embed Size (px)
Citation preview
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 1 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 2 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 3 -
C++ InheritanceC++ Inheritance
Inheritance
Inheritance is a familiar concept….
Inherit From parents
In Biology
Kingdom
Phylum
Class
Order
Family
Genus
Species
Vehicles
Land BasedAuto Bicycle
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 4 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 5 -
C++ InheritanceC++ Inheritance
Inheritance
Vehicle
Class
Land Based
Bicycles Autos
myVehicle
myLandBased
myAuto myBicycle
Instance
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 6 -
C++ InheritanceC++ Inheritance
Inheritance
Instance hierarchy follows the class hierarchy
Single InheritanceEach object has a single parent
Class
Instance
Multiple InheritanceClasses inherit from multiple base classes
Defines a relationship
Between several (independent) class types
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 7 -
C++ InheritanceC++ Inheritance
Multiple InheritanceVehicleVehicle
Land BasedLand Based
AutomobileAutomobile Motor BoatMotor Boat
AutoBoatAutoBoat
Water BasedWater Based
Multiple Parents Common Ancestor
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 8 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 9 -
C++ InheritanceC++ Inheritance
Virtual InheritanceThe derived class AutoBoat……
Inherits Attributes and Properties
From
Automobile
Motor Boat
Vehicle
VehicleVehicle
Land BasedLand Based
AutomobileAutomobile Motor BoatMotor Boat
AutoBoatAutoBoat
Water BasedWater Based
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 10 -
C++ InheritanceC++ Inheritance
Inheritance - Derivation Hierarchy
The class vehicle is an abstraction…..
It represents an encapsulation of commonProperties
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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 11 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 12 -
C++ InheritanceC++ 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 BaseClassNameDerivedClassName - the class being derivedspecification - specifies access to the base class
memberspublicprotectedprivate
- private by default
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 13 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 14 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 15 -
C++ InheritanceC++ Inheritance
C++ Class Derivationclass A : private B
In class AThe inherited public members of BAppear as private members of A
if myValue is a public data member of BmyValue 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 16 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 17 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 18 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 19 -
C++ InheritanceC++ 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 listIf no constructor in the base class use the default
If the base class is derived the procedure applied recursively
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 20 -
C++ InheritanceC++ Inheritance
C++ Class Derivation - Constructors and DestructorsInherited Member Initialization
If the base class has only a default constructorInitialize the member values in body of the derived class constructor
If the base class has constructor with argumentsThe initialization list is used to pass arguments to the base class constructors
syntax
DerivedClass ( derivedClass args ) : BaseClass ( baseClass args ){
DerivedClass constructor body}
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 21 -
C++ InheritanceC++ 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 accessesa self c2 c1
b self c2 c1
c self c2
d self
e self c2
C1
C1
C2
C2
C3
C3
data member afunction member b()function member c()function member d()
function member c()function member e()
function member d()
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 22 -
C++ InheritanceC++ 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)
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 23 -
C++ InheritanceC++ 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 ispublic
public members remain public
protected members remain protected
protected
inherited non-private members accessible as protected
private
no outside access
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 24 -
C++ InheritanceC++ 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.
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 25 -
C++ InheritanceC++ Inheritance
C++ Class DerivationDerivation Guidelines
1. Derivation is not always the best way to extend the system.
2. Use public derivationWhen the derived object is a kind of (AKO) base class
3. Use private derivationWhen the derived object is not a kind of base class but
derivation makes code development easier.
4. Use protected derivationWhen private derivation is suitable but member access
from further derived classes is desirable.
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 26 -
C++ InheritanceC++ 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.
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 27 -
C++ InheritanceC++ Inheritance
C++ Class Derivation - Member LayoutSingle Inheritance
struct A
{int a1;
void af ( );
};
struct B : A
{int b1;
void bf1 ( );
};
B :: b1
A*, B* ->
A :: a1 A* ->
A :: a1
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 28 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 29 -
C++ InheritanceC++ Inheritance
C++ Class Derivation - Member Layout
Virtual Inheritance
struct E : virtual A
{int e1;
void ef ( );
};
E :: vbptr
E :: e1
E* ->
SharedMembers
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 30 -
C++ InheritanceC++ Inheritance
C++ Class Derivation - Private Derivation
If the derivation specification is changed to….. class BaseClass{public:
BaseClass() {baseValue = 20;}int baseValue;
};
class DerivedClass : private BaseClassmain (void){
DerivedClass child;child.baseValue = 30; // compile error
}
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 31 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 32 -
C++ InheritanceC++ 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 protectedActs as
public member to Member functions and friends of derived
classprivate member to
The rest of the program
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 33 -
C++ InheritanceC++ Inheritance
C++ Class Derivation - Conversions Under DerivationThere 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.
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 34 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 35 -
C++ InheritanceC++ 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
1
4
2
3
stem
stem
skin
fp -> stem
((Apple *) fp) -> stem
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 36 -
C++ InheritanceC++ Inheritance
Overloaded Functions with Class Type Arguments
Overloaded Function Call Resolution
Exact MatchA 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 37 -
C++ InheritanceC++ Inheritance
Overloaded Functions with Class Type Arguments
Overloaded Function Call Resolution
Standard Conversions - Object ConversionA 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 38 -
C++ InheritanceC++ Inheritance
Overloaded Functions with Class Type Arguments
Overloaded Function Call Resolution
Standard Conversions - void ConversionA 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 39 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 40 -
C++ InheritanceC++ Inheritance
Copy Constructors and DerivationIf 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 41 -
C++ InheritanceC++ 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 PathUse the function in the most immediate scope for
which the
signatures are identical
Multiple PathsUse the scope operator or virtual functions
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 42 -
C++ InheritanceC++ Inheritance
Multiple Base Classes
A derived class can inherit from multiple base classes….
syntaxclass 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 43 -
C++ InheritanceC++ 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
Copyright 2006 Oxford Consulting, Ltd
1 February 2006
- 44 -
C++ InheritanceC++ 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
syntaxDerivedClass ( dCl args ) : BC0 (bC0 args), BC1 (bC1 args), ...BCn
( bCn args),{
DerivedClass constructor body
}