learners support publications inheritance: extending classes

49
Learners Support Publications www.lsp4you.com Inheritance: Inheritance: Extending Classes Extending Classes

Upload: hope-robbins

Post on 18-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

Learners Support Publicationswww.lsp4you.com

Inheritance: Extending Inheritance: Extending ClassesClasses

Learners Support Publicationswww.lsp4you.com

IntroductionIntroduction

Reusability is an important feature of Reusability is an important feature of OOP.OOP.

C++ strongly supports the concept C++ strongly supports the concept of reusability.of reusability.

Learners Support Publicationswww.lsp4you.com

IntroductionIntroduction

The mechanism of deriving a new The mechanism of deriving a new class from an old one is called class from an old one is called inheritance (or derivation).inheritance (or derivation).

The old class is referred to as base The old class is referred to as base class.class.

The new class is called the derived The new class is called the derived class or subclass.class or subclass.

continue …

Learners Support Publicationswww.lsp4you.com

IntroductionIntroduction

The derived class inherits some or all The derived class inherits some or all of the traits from the base class.of the traits from the base class.

A class can also inherit properties A class can also inherit properties from more than one class or from from more than one class or from more than one level.more than one level.

continue …

Learners Support Publicationswww.lsp4you.com

Single InheritanceSingle Inheritance

A derived class with only one base A derived class with only one base class.class.

A

B

Learners Support Publicationswww.lsp4you.com

Multiple InheritanceMultiple Inheritance

A derived class with several base A derived class with several base classes.classes.

A

C

B

Learners Support Publicationswww.lsp4you.com

Hierarchical InheritanceHierarchical Inheritance

A traits of one class may be inherited A traits of one class may be inherited by more than one class.by more than one class.

A

B C D

Learners Support Publicationswww.lsp4you.com

Multilevel InheritanceMultilevel Inheritance

The mechanism of deriving a class The mechanism of deriving a class from another derived class.from another derived class.

A

C

B

Learners Support Publicationswww.lsp4you.com

Hybrid InheritanceHybrid Inheritance

The mechanism of deriving a class by The mechanism of deriving a class by using a mixture of different methods.using a mixture of different methods.

A

D

B C

Learners Support Publicationswww.lsp4you.com

Derived ClassesDerived Classes

A derived class can be defined by A derived class can be defined by specifying its relationship with the specifying its relationship with the base class in addition to its own base class in addition to its own details.details.

classclass derived-class-namederived-class-name :: visibility-mode visibility-mode base-class-namebase-class-name

{{

………………////

………………// members of derived class// members of derived class

………………////

};};

Learners Support Publicationswww.lsp4you.com

Derived ClassesDerived Classes

classclass derived-class-namederived-class-name :: visibility-mode visibility-mode base-class-namebase-class-name

{{

………………////

………………// members of derived class// members of derived class

………………////

};};

The colon indicates that the derived-class-name is derived from the base-class-name

The visibility mode is optional and , if present, may be either private or public.

The default visibility mode is private.

Visibility mode specifies whether the features of the base class are derived privately or publicly.

continue …

Learners Support Publicationswww.lsp4you.com

Derived ClassesDerived Classes

When a base class is privately derived by a When a base class is privately derived by a derived class, “public members” of the base class derived class, “public members” of the base class become “private members” of the derived class.become “private members” of the derived class.

Therefore the members of the derived class can Therefore the members of the derived class can only access the public members of the base class.only access the public members of the base class.

They are inaccessible to the objects of the They are inaccessible to the objects of the derived class.derived class.

No member of the base class is accessible to the No member of the base class is accessible to the objects of the derived class.objects of the derived class.

continue …

Learners Support Publicationswww.lsp4you.com

Derived ClassesDerived Classes

When a base class is publicly inherited, When a base class is publicly inherited, ”public members” of the base class ”public members” of the base class become the “public members” of the become the “public members” of the derived class.derived class.

They are accessible to the objects of the They are accessible to the objects of the derived class.derived class.

continue …

Learners Support Publicationswww.lsp4you.com

Derived ClassesDerived Classes

The private members of the base class are The private members of the base class are not inherited in both the cases not inherited in both the cases (publicly/privately inherited).(publicly/privately inherited).

The private members of a base class will The private members of a base class will never become the members of its derived never become the members of its derived class.class.

continue …

Learners Support Publicationswww.lsp4you.com

InheritanceInheritance

In inheritance, some of the base class data In inheritance, some of the base class data elements and member functions are inherited elements and member functions are inherited into the derived class.into the derived class.

We can add our own data and member functions We can add our own data and member functions for extending the functionality of the base class.for extending the functionality of the base class.

It is a powerful tool for incremental program It is a powerful tool for incremental program development.development.

Can increase the capabilities of an existing class Can increase the capabilities of an existing class without modifying it.without modifying it.

Learners Support Publicationswww.lsp4you.com

Single InheritanceSingle Inheritance

A

B

Learners Support Publicationswww.lsp4you.com

Making a Private Member InheritableMaking a Private Member Inheritable

By making the visibility limit of the private By making the visibility limit of the private members to the public.members to the public.

The visibility modifier “protected” can be used for The visibility modifier “protected” can be used for this purpose.this purpose.

A member declared as “protected” is accessible A member declared as “protected” is accessible by the member functions within its class and any by the member functions within its class and any class immediately derived from it.class immediately derived from it.

It can not be accessed by the functions outside It can not be accessed by the functions outside these two classes.these two classes.

Learners Support Publicationswww.lsp4you.com

Making a Private Member InheritableMaking a Private Member Inheritable

class alphaclass alpha{{

private :private : // optional// optional

……… ……… // visible to the member within its class// visible to the member within its class

……………… protected :protected :

……………… // visible to member functions// visible to member functions

……………… // of its own and immediate derived class// of its own and immediate derived class

public :public :……………… // visible to all functions// visible to all functions

……………… // in the program// in the program

};};

continue …

Learners Support Publicationswww.lsp4you.com

Protected MemberProtected Member

When a protected When a protected member is inherited in member is inherited in public mode, it public mode, it becomes protected in becomes protected in the derived class.the derived class.

They are accessible by They are accessible by the member functions the member functions of the derived class.of the derived class.

And they are ready for And they are ready for further inheritance.further inheritance.

When a protected When a protected member is inherited in member is inherited in private mode, it private mode, it becomes private in becomes private in the derived class.the derived class.

They are accessible by They are accessible by the member functions the member functions of the derived class.of the derived class.

But, they are not But, they are not available for further available for further inheritance.inheritance.

continue …

Learners Support Publicationswww.lsp4you.com

Protected DerivationProtected Derivation

It is possible to inherit a base class in It is possible to inherit a base class in protected mode – protected mode – protected derivationprotected derivation..

In protected derivation, both the In protected derivation, both the publicpublic and and protectedprotected members of the base class members of the base class become become protectedprotected members of the derived members of the derived class.class.

Learners Support Publicationswww.lsp4you.com

Effect of Inheritance on the visibility of MembersEffect of Inheritance on the visibility of Members

Private

Protected

Public

Private

Protected

Public

Private

Protected

Private

Protected

Public Public

Not inheritableNot inheritable

Class B

Class D1 : public B Class D2 : private B

Class X : public D1, protected D2

Learners Support Publicationswww.lsp4you.com

VisibilityVisibility

Base class Base class visibilityvisibility

Derived class visibilityDerived class visibility

Public Public DerivationDerivation

Private Private DerivationDerivation

Protected Protected DerivationDerivation

Private Private Not Not InheritedInherited

Not Not InheritedInherited

Not Not InheritedInherited

Protected Protected ProtectedProtected PrivatePrivate ProtectedProtected

Public Public PublicPublic PrivatePrivate ProtectedProtected

Learners Support Publicationswww.lsp4you.com

Access Control to Data MembersAccess Control to Data Members

Functions that can have access to the Functions that can have access to the

privateprivate and and protectedprotected members of a class: members of a class:

• A function that is a friend of the class.A function that is a friend of the class.

• A member function of a class that is a friend of A member function of a class that is a friend of the class.the class.

• A member function of a derived class.A member function of a derived class.

Learners Support Publicationswww.lsp4you.com

Access mechanism in classesAccess mechanism in classes

fx1

fx2

fy1

fy2

fz1

fz2

data

data

class Xclass Y

class Z

friend of X

friend of X

Inherited from X

friend class Y: private

protected

Function 1

Learners Support Publicationswww.lsp4you.com

Multilevel InheritanceMultilevel Inheritance

The class A serves as a The class A serves as a

base class for the derived base class for the derived

class B, which in turn class B, which in turn

serves as a base class for serves as a base class for

the derived class C.the derived class C.

Class B provides a link for Class B provides a link for

the inheritance between A the inheritance between A

and C.and C.

The chain ABC is known as The chain ABC is known as

inheritance path.inheritance path.

C

Base Class

Derived Class

A

BIntermediateBase Class

Learners Support Publicationswww.lsp4you.com

Multilevel InheritanceMultilevel Inheritance

class A { ………} ; // Base Classclass A { ………} ; // Base Class

class B : public A { ……… } ; // B derived from Aclass B : public A { ……… } ; // B derived from A

class C : public B { ……… } ; // C derived from Bclass C : public B { ……… } ; // C derived from B

continue …

Learners Support Publicationswww.lsp4you.com

Multiple InheritanceMultiple Inheritance

A class can inherit the A class can inherit the attributes of two or attributes of two or more classes.more classes.

Multiple inheritance Multiple inheritance allows us to combine allows us to combine the features of several the features of several existing classes as a existing classes as a starting point for starting point for defining new classes.defining new classes.

It is like a child It is like a child inheriting the physical inheriting the physical features of one parent features of one parent and the intelligence of and the intelligence of another.another.

B-1

D

B-2

Learners Support Publicationswww.lsp4you.com

Multiple InheritanceMultiple Inheritance

class D: visibility B-1, visibility B-2, ……class D: visibility B-1, visibility B-2, ……

{{

………………

……… ……… (Body of D)(Body of D)

………………

};};

Where, visibility may be either public or private.Where, visibility may be either public or private. The base classes are separated by comma.The base classes are separated by comma.

continue …

Learners Support Publicationswww.lsp4you.com

Ambiguity Resolution in InheritanceAmbiguity Resolution in Inheritance

class Mclass M

{{

public:public:

void display (void)void display (void)

{ cout << “Class M \n“;}{ cout << “Class M \n“;}

};};

class Nclass N

{{

public:public:

void display (void)void display (void)

{ cout << “Class N \n“;}{ cout << “Class N \n“;}

};};

class P : public M, public Nclass P : public M, public N

{{

public:public:

void display (void)void display (void)

{ M :: display();}{ M :: display();}

};};

void main( )void main( )

{{

P p;P p;

p.display( );p.display( );

}}

In Multiple Inheritance

Learners Support Publicationswww.lsp4you.com

Ambiguity Resolution in InheritanceAmbiguity Resolution in Inheritance

class Aclass A

{{

public:public:

void display (void)void display (void)

{ cout << “Class A \n“;}{ cout << “Class A \n“;}

};};

class B : public Aclass B : public A

{{

public:public:

void display (void)void display (void)

{ cout << “Class B \n“;}{ cout << “Class B \n“;}

};};

void main( )void main( )

{{

B b;B b;

b.display( );b.display( ); // in B// in B

b.A::display( );b.A::display( ); // in A// in A

b.B::display( );b.B::display( ); // in B// in B

}}

Ambiguity can be resolved by Ambiguity can be resolved by specifying the function with specifying the function with class name and scope class name and scope resolution operator to invoke.resolution operator to invoke.

continue …

In Single Inheritance

Learners Support Publicationswww.lsp4you.com

Hierarchical InheritanceHierarchical Inheritance Inheritance support Inheritance support

hierarchical design of a hierarchical design of a program.program.

Additional members are Additional members are added through inheritance to added through inheritance to extend the capabilities of a extend the capabilities of a class.class.

Programming problems can Programming problems can be cast into a hierarchy where be cast into a hierarchy where certain features of one level certain features of one level are shared by many others are shared by many others below that levelbelow that level

FD

STD

MTD

LTD

Account

SB CA

Learners Support Publicationswww.lsp4you.com

Hybrid InheritanceHybrid Inheritance

Applying Two or more Applying Two or more types of inheritance types of inheritance together.together.

test

result

student

sports

Learners Support Publicationswww.lsp4you.com

Virtual Base ClassesVirtual Base Classes

Here the Here the result classresult class has two direct base has two direct base classes classes testtest and and sportssports which themselves which themselves have a common base have a common base class class studentstudent..

The The result result inherits the inherits the traits of traits of studentstudent via via two separate paths.two separate paths.

test

result

student

sports

Learners Support Publicationswww.lsp4you.com

Virtual Base ClassesVirtual Base Classes

It can also inherit It can also inherit directly as shown by directly as shown by the broken line.the broken line.

The The student classstudent class is is referred to as referred to as indirect indirect base classbase class..

continue …

test

result

student

sports

Learners Support Publicationswww.lsp4you.com

Virtual Base ClassesVirtual Base Classes

All the All the publicpublic and and protectedprotected members of members of studentstudent are inherited are inherited into result twice, first into result twice, first via via testtest and again via and again via sportssports..

This means This means result result classclass have duplicate have duplicate set of members set of members inherited from inherited from studentstudent..

continue …

test

result

student

sports

Learners Support Publicationswww.lsp4you.com

Virtual Base ClassesVirtual Base Classesclass studentclass student{{

………………};};class test : virtual public studentclass test : virtual public student{{

………………};};class sports : public virtual studentclass sports : public virtual student{{

………………};};class result : public test, public sportsclass result : public test, public sports{{

………………\\};};

continue …

test

result

student

sports

Learners Support Publicationswww.lsp4you.com

Abstract ClassesAbstract Classes

An abstract class is one that is not used to create An abstract class is one that is not used to create

objects.objects.

An abstract class is designed only to act as a An abstract class is designed only to act as a

base class.base class.

It is a design concept in program development It is a design concept in program development

and provides a base upon which other classes and provides a base upon which other classes

may be built.may be built.

Learners Support Publicationswww.lsp4you.com

Constructors in Derived ClassesConstructors in Derived Classes

If no base class constructor takes any arguments, If no base class constructor takes any arguments,

the derived class need not have a constructor the derived class need not have a constructor

function.function.

If any base class contains a constructor with one If any base class contains a constructor with one

or more arguments, then it is mandatory for the or more arguments, then it is mandatory for the

derived class to have a constructor and pass the derived class to have a constructor and pass the

arguments to the base class constructors.arguments to the base class constructors.

Learners Support Publicationswww.lsp4you.com

Constructors in Derived ClassesConstructors in Derived Classes

When both the derived and base class contain When both the derived and base class contain

constructors, the base constructor is executed constructors, the base constructor is executed

first and then the constructor in the derived class first and then the constructor in the derived class

is executed.is executed.

In case of multiple inheritance, the base class In case of multiple inheritance, the base class

constructors are executed in the order in which constructors are executed in the order in which

they appear in the declaration of the derived they appear in the declaration of the derived

class.class.

continue …

Learners Support Publicationswww.lsp4you.com

Constructors in Derived ClassesConstructors in Derived Classes

In a multilevel inheritance, the constructors will In a multilevel inheritance, the constructors will

be executed in the order of inheritance.be executed in the order of inheritance.

Since the derived class takes the responsibility of Since the derived class takes the responsibility of

supplying initial values to its base classes, we supplying initial values to its base classes, we

supply the initial values that are required by all supply the initial values that are required by all

the classes together, when a derived class object the classes together, when a derived class object

is declared.is declared.

continue …

Learners Support Publicationswww.lsp4you.com

Constructors in Derived ClassesConstructors in Derived Classes

The constructor of the derived class receives the The constructor of the derived class receives the

entire list of values as its arguments and passes entire list of values as its arguments and passes

them on to the base constructors in the order in them on to the base constructors in the order in

which they are declared in the derived class.which they are declared in the derived class.

The base constructors are called and executed The base constructors are called and executed

before executing the statements in the body of before executing the statements in the body of

the derived constructor.the derived constructor.

continue …

Learners Support Publicationswww.lsp4you.com

Constructors in Derived ClassesConstructors in Derived Classes

The header line of The header line of derived-constructorderived-constructor

function contains two parts separated by function contains two parts separated by

a colon (:).a colon (:).

• The first part provides the declaration of the The first part provides the declaration of the

arguments that are passed to the derived arguments that are passed to the derived

constructor.constructor.

• The second part lists the function calls to the The second part lists the function calls to the

base constructors.base constructors.

continue …

Learners Support Publicationswww.lsp4you.com

Defining Derived ConstructorsDefining Derived Constructors

Derived-constructor(Arglist1, Arglist2, … ArglistN, Derived-constructor(Arglist1, Arglist2, … ArglistN,

ArglistD) : ArglistD) :

base1(arglist1), base1(arglist1),

base2(arglist2), base2(arglist2),

… …

baseN(arglistN)baseN(arglistN)

{{

}}

continue …

Learners Support Publicationswww.lsp4you.com

Member Classes : Nesting of ClassesMember Classes : Nesting of Classes

Inheritance is the mechanism of deriving Inheritance is the mechanism of deriving

certain properties of one class into certain properties of one class into

another.another.

C++ supports a new way of inheriting C++ supports a new way of inheriting

classes:classes:

• An object can be collection of many other An object can be collection of many other

objects.objects.

• A class can contain objects of other classes A class can contain objects of other classes

as its members.as its members.

Learners Support Publicationswww.lsp4you.com

Member Classes : Nesting of ClassesMember Classes : Nesting of Classes

class alpha { ……… };class alpha { ……… };

class beta { ……… };class beta { ……… };

class gammaclass gamma

{{

alpha a;alpha a; // an object of class alpha// an object of class alpha

beta b;beta b; // an object of class beta// an object of class beta

………………

};};

continue …

Learners Support Publicationswww.lsp4you.com

Member Classes : Nesting of ClassesMember Classes : Nesting of Classes

class alpha { ……… };class alpha { ……… };

class beta { ……… };class beta { ……… };

class gammaclass gamma

{{

alpha a;alpha a;

beta b;beta b;

………………

};};

All objects of All objects of gamma class will gamma class will contain the objects contain the objects a and b.a and b.

This is called This is called containershipcontainership or or nestingnesting..

continue …

Learners Support Publicationswww.lsp4you.com

Member Classes : Nesting of ClassesMember Classes : Nesting of Classes

An independent object is created by its An independent object is created by its

constructor when it is declared with arguments.constructor when it is declared with arguments.

A nested object is created in two stages:A nested object is created in two stages:

• The member objects are created using their The member objects are created using their

respective constructors.respective constructors.

• Then ordinary members are created.Then ordinary members are created.

Constructors of all the member objects should Constructors of all the member objects should

be called before its own constructor body is be called before its own constructor body is

executed.executed.

continue …

Learners Support Publicationswww.lsp4you.com

Member Classes : Nesting of ClassesMember Classes : Nesting of Classes

class gammaclass gamma

{{

……… ………

alpha a;alpha a;

beta b;beta b;

public:public:

gamma(arglist): alpha(arglist1), beta(arglist2)gamma(arglist): alpha(arglist1), beta(arglist2)

{ body of the constructor }{ body of the constructor }

};};

continue …

Learners Support Publicationswww.lsp4you.com

Thank YouThank You

Learners Support PublicationsLearners Support Publications

www.lsp4you.comwww.lsp4you.com