You are on page 1of 22

CSC-210

OBJECT ORIENTED PROGRAMMING

ABDUL ATTAYYAB KHAN


EMAIL ADDRESS: AAKHAN.BUKC@bahria.edu.pk
WEBSITE: https://sites.google.com/view/oopbukc/course-contents

Inheritance

1
CONTENTS
 What is Inheritance.
 Single Inheritance.
 Access Modifiers.
 Protected Modifier.

 Multiple Level Inheritance.


 Protected Access.

 Public/Non-public Derivations.
 General Syntax of Class Inheritance.

 Types of Inheritance.
 Public Inheritance.
 Private Inheritance.
 Protected Inheritance.

 Calling Sequence for Constructors and Destructors.


 Parameter Passing to Superclass Constructors.

WHAT IS INHERITANCE
 Inheritance is one of the main characteristics of an object-oriented
language.
 In object-oriented programming, if we wish to inherit the functionality of an
existing class, we define new class based on an existing class.
 The existing class whose functionality is inherited is called the base class
and the new class that inherits the functionality is called a derived class.
 The base class acts like parent and the derived class becomes its child.
 The important advantage of inheritance is the reusability of the code. Once
a base class is defined and fully tested its functionality can be reused in a
derived TO
CLICK class.EDIT MASTER TITLE STYLE

2
SINGLE INHERITANCE
 Consider the following definition for a Point class.

CLICK TO EDIT MASTER TITLE STYLE


 The important advantage of inheritance is the reusability of the code. Once
a base class is defined and fully tested its functionality can be reused in a
derived class.

SINGLE INHERITANCE
 The scheme of (single) inheritance is illustrated in figure:

Class name Point


Attributes int x;
int y;
setX ( ) { };
setY ( ) { };
Methods int getX ( ) { };
int getY ( ) { };

Class name ColorPoint

Attributes int color;

setColor ( ) { };
Methods
CLICK TO EDIT MASTER TITLE STYLE
int getColor ( ) { };

3
SINGLE INHERITANCE
 The definition of ColorPoint class is given below:

 Note the declaration statement for the ColorPoint class:


Class ColorPoint:public Point
 The colon (‘ : ‘) indicates that our new class ColorPoint will inherit from the class
specified on the right-hand side of the colon.
CLICK TO EDIT MASTER TITLE STYLE
 When a class inherits from some other class, it will derive the functionality of the
base class as if it were its own functionality.
 Thus, the ColorPoint class will exhibit the get/set methods for
access/modification of x, y attributes as if those are defined for the ColorPoint
class itself.

SINGLE INHERITANCE
 We will now write a main function to test our classes.
void main()
{
Point p;

 In the main function, first we create an object of Point class. We call set methods
of the Point class to set the values of x and y members.
p.setx(10);
p.sety(10);

 We print the current values of x, y on the user console by calling the get
methods of the Point class:
cout<<“Point p:(“ << p.getx() << “,” << p.gety() <<“)”<< endl;
CLICK TO EDIT MASTER TITLE STYLE
 We now declare a variable of class ColorPoint:
ColorPoint clrPt;

 As the ColorPoint class inherits from Point class, it will have access to the public
methods of the Point class.

4
SINGLE INHERITANCE
 We now use the inherited methods to set the x, y coordinates of the
ColorPoint object.
clrPt.setx(20);
clrPt.sety(20);

 Note that we have not defined setx, sety methods in the ColorPoint class.
These are the methods of the Point class that the ColorPoint class has inherited.
 We now set the color value for our point by calling the setColor method of the
ColorPoint class.
clrPt.setColor(0);

 We will print the x, y coordinates by calling the inherited get methods:

CLICK TO EDIT MASTER TITLE STYLE


cout<<“ColorPoint p:(“ <<clrPt.getx() << “,” <<clrPt.gety() << “)” << endl;

 The get methods are not defined in the ColorPoint class and are inherited from the
base class Point.
 To print the color value, we call the getColor method of the ColorPoint class.
cout << “ColorPoint color: “ << clrPt.getColor() << endl;

SINGLE INHERITANCE

CLICK TO EDIT MASTER TITLE STYLE

5
ACCESS MODIFIER
 We have seen two types of access modifiers– public and private.
 The public and private access modifiers control the visibility of the class members.
 One more access modifier called protected. The protected modifier also
controls the visibility of the class members, however, it becomes meaningful only
when we use inheritance.

CLICK TO EDIT MASTER TITLE STYLE

ACCESS MODIFIER
 PUBLIC: If a class member is declared using public access modifier, it is accessible
to any program code defined inside the class, defined in an inherited class or
defined outside the class.
 PRIVATE: In case of private access modifiers, such members will be visible only
within the current class definition.
 PROTECTED: When we create a class hierarchy by inheritance, we will like to make
certain members of the base class accessible to all its children, yet make them
inaccessible to any code that is defined outside this hierarchy of classes. This is
achieved by using the protected keyword.

CLICKTable: Variable visibility for different access specifiers


TO EDIT MASTER TITLE STYLE
Access specifies Same class Derived class Outside code
Public ✓ ✓ ✓
Private ✓ ✗ ✗
Protected ✓ ✓ ✗

6
ACCESS MODIFIER
Protected Modifier
 Consider the following class declaration:

 The class definition contains three sections : private, protected and


public.
CLICK TO EDIT MASTER TITLE STYLE
 The two data members x, y are declared in the private section and thus
will be accessible only to the code within the class definition.
 The setx and getx methods are defined with protected scope and sety,
gety are defined with public scope.

ACCESS MODIFIER
 We will derive a class from this base class A to understand the protected scope.
Let us create a class B that inherits from class A using following declaration:
class B:public A
 The object of class B will have access to public methods of class A. Thus, the
following method calls are valid:
B ObjectB;
ObjectB.sety(20);
int y = ObjectB.gety();
 What if we call the protected method using the above object reference? The
following calls would be illegal:
CLICK TO EDIT MASTER TITLE STYLE
ObjectB.setx(20); //illegal call
int x = ObjectB.getx(); //illegal call
 As both methods setx, getx are declared using protected, i.e. outside the
base class and its subclasses.

7
ACCESS MODIFIER
 So, how does the outside code use this method?
 For this, we will write a public method in the subclas B that internally calls the
protected method of class A. The method definition is shown below:

 We define a new method called getXCoordinate in our subclass B.


 The implementation of this method calls the protected getx method of the base
CLICK
class A. TO EDIT MASTER TITLE STYLE
 The method getx is surely visible in class B as class B publicly inherits from class A.

ACCESS MODIFIER
 The outside program code can now obtain the value of x-coordinate by using the
following code:
B ObjectB;
int x = ObjectB.getxCoordinate();
cout << x << endl;
 A protected class member is visible to the defining class and its immediate
subclasses.

CLICK TO EDIT MASTER TITLE STYLE

8
ACCESS MODIFIER
 The functionality of the protected modifier is shown in figure.. The figure shows the valid
and the invalid calls made from class B on the members of class A.
Class A
private:
int x;
int y;
protected:
setX ( ) { };
getX ( ) { };
public:
setY ( ) { };
getY ( ) { };

Invalid Call
Public Inheritance of ClassA
Class B
Valid Call Inherited Protected & Public members

int getXCoordinate() {
return getX();}
void setXCoordinate(int x){
setx(x);}

CLICK TO EDIT MASTER TITLE STYLE


void main()
Valid Call

{
Outside code B ObjectB;
ObjectB.setXCoordinate(10);
int x=OnjectB.getXCoordinate();

ObjectB.setx(20);
int x=ObjectB.getx();}

Functionality of protected modifier

ACCESS MODIFIER

CLICK TO EDIT MASTER TITLE STYLE

9
MULTIPLE LEVEL INHERITANCE
 It is possible to extend the functionality of a derived class by deriving further classes
from it. This is known as multiple level inheritance.
 Consider the class definition as follows:

 We now derive class B from class A using the above declaration.


 We further derive class C from class B.
 In the above example we have multiple level of inheritance.
CLICK TO EDIT MASTER TITLE STYLE

MULTIPLE LEVEL INHERITANCE


 Now let us study the effect of base class member visibilty to its subclasses.
 Class A defines two private data members x and y. These will be visible only to the
code defined in class A and not to the subclassess of class A.
 Thus, these variables cannot be accessed directly by the code defined in class B or
class C.
 The members are also obviously invisible to any code outside the class A definition.

CLICK TO EDIT MASTER TITLE STYLE

10
MULTIPLE LEVEL INHERITANCE
 Now let us study the effect of base class Class A
member visibilty to its subclasses. private:
int x;
int y;
 Class A defines two private data members x
public:
and y. These will be visible only to the code setx ( )
defined in class A and not to the subclassess getx ( )
sety ( )
of class A.
Public inheritance from class A
 Thus, these variables cannot be accessed
Class B
directly by the code defined in class B or
class C. Inherits all
public members
 The members are also obviously invisible to of Class A
any code outside the class A definition.
Public inheritance from class B
 Class A defines four public methods, getx,
CLICK TO EDIT MASTER TITLE STYLE
setx, gety and sety. Class C

 All these methods will be visible to the code Inherits all


public members
defined in class B or class C. of Class B
 Also, these methods will be visible to the
code defined outside any of the above Multiple level of inheritance
classes.

MULTIPLE LEVEL INHERITANCE


Protected Access
 Now, what happens if we define some of the members of class A as protected?
 Let us consider that we declare getx method as protected rather than public.
 We will study the visibility of getx method to the code defined outside class A.
protected:
int getx();
 The method is visible to any code in class B or class C.
 Thus, if class B contains a method definition as follows, it can use getx method of class A.

CLICK TO EDIT MASTER TITLE STYLE


 Similarly, a method implementation in class C too can get use getx method of class A.

11
MULTIPLE LEVEL INHERITANCE
 Now what if we declare a main method that
creates an object of class B or class C and Class A
uses this object reference to invoke getx private Invisible to B, C
and Outside code
method of class A.
protected
 As the method is declared protected, the
public
method would not be accessible to an
Public inheritance
object of subclass. Protected members Protected members
visible to B and C but visible to B, C
Class B
 The following code fragement Not to Outside code and any
Outside code
illustrates this: Class
Implementation
Code

Public inheritance
Class C
CLICK TO EDIT MASTER TITLE STYLE Class
Implementation
Code

MULTIPLE LEVEL INHERITANCE

 Note that ObjectC of type C has


access to inherited setx method s this
CLICK TO EDIT MASTER TITLE STYLEis declared public in the base class.
 However, ObjectC does not have an
access to getx method that I declared
protected in the base class.
 If we uncomment line 40 the compiler
will give compilation error.

12
PUBLIC/NON-PUBLIC DERIVATIONS
 So far, all our class derivations were public.
 We will first study the general syntax of inheritance and then look up the effect of
non-public derivations.
General Syntax of Class Inheritance:
 The general syntax of class inheritance is shown below
class classname: AccessModifier baseclassname
 The classname specifies the name for the derived class.
 The baseclassname specifies the name of the base class and the AccessModifier
defines the mode of access for the base class members by the derived class.

CLICK TO EDIT MASTER TITLE STYLE

TYPES OF INHERITANCE
 When we inherit from an existing class, we derive the functionality of the class from
which we inherit.
 However, we may decide not to pass on the privileges we have gained to our
subclasses.
 Accordingly, we may decide to on the type of inheritance while inheriting from an
existing class.
 The three types of inheritance are:
• Public
• Private
• Protected
CLICK TO EDIT MASTER TITLE STYLE

13
Public Inheritance TYPES OF INHERITANCE
 Consider the following definition:

 The class A defines two data members x and y. These two data members have private
scope by default.
 However, to make it explicit, these have been defined under the private section of the
class.
 Thus, these two members would be accessible only to methods of the current class.
CLICK TO EDIT MASTER TITLE STYLE
 We now derive a class based on the above class A as follows:
class B: public A
 The class B above inherits from class A using public access modifier.

TYPES OF INHERITANCE
 Now, let us study what is inherited.
 The class B would inherit all the public methods of class A.
 If we create an object of class B, we would be able to apply the setx, getx, sety
and gety methods on this object. The following statements are valid:
B ObjectB;
ObjectB.getx();
ObjectB.sety();
 However, the following statement would be invalid:
ObjectB.x =10; //invalid
 This is invalid because the object of a derived class is trying to access the private
CLICK TOtheEDIT
member of MASTER TITLE STYLE
base class.
 Similarly, trying to access the data member y of the Point class through the reference
of a derived class object would be invalid.
 Thus, the following statement is invalid too:
int y= ObjectB.y; //invalid

14
TYPES OF INHERITANCE
 Whatever applies to the private data
members also applied to the private
methodsof the base class.
 In the Point class, if we define say getx,
method as private to the Point class by
declaraing it in private section, the
method would not be accessible to the
derived class object.
 The scheme of public inheritance is shown
in Figure.
 In public inheritance, the derived class has
CLICK
access to TO EDIT
all the publicMASTER TITLE
methods and the STYLE
data members of the base class.
 The derived class cannot access the private
methods and data members of the base
class.
Public inheritance

TYPES OF INHERITANCE
Private Inheritance
 Considering the class definition for class A as given in the previous section, we will
now derive class B from class A as follows:
class B: private A
 Note that we have used private access modifier in place of public modifier in our class
derivation.
 When we inherit using private keyword, all the protected and public members of the
base class will become private to the derived class.
 Thus, the code in derived class will be able to access these members. The following
method definition is valid:

CLICK TO EDIT MASTER TITLE STYLE

15
TYPES OF INHERITANCE
 Note that the derived class cannot pass these Class A
inherited members to further derived classes. Private
Let us consider the following derivation:
Protected
class C: public B
Public
 Here class C publicly inherits from class B as Private inheritance from class B
shown in figure. Class B
 Thus, all the protected and public members of Private
class B would be visible in class C and private
Protected
members of class B will not be accessible to
class C. Public

 If we now define a method in class C that tries


to use getx method, it would be illegal access as Inherits all public &
protected members of
shown in the code further: Class A as Private
Not accessible
CLICK TO EDIT MASTER TITLE STYLE
Public inheritance from class C
Class C
Inherits all public &
protected members of
Class A and Class B as
public & protected
respectively.

 If we try to compile the above class definition,


Private inheritance
the compiler will throw an error

TYPES OF INHERITANCE
Class A
Protected Inheritance private

protected
 In the previous derviation of class B, what
would happen if we use protected modifier public
in case of private modifer? The declaration Protected inheritance from
class B
is given below: Class B
private
class B: protected A protected

 The class B inherits all the public and public


Inherits all protected
protected methods of class A and treats members of Class A as
them as protected within its own definition. protected & public as
protected
This is represented in figure.
Public inheritance from class C
Not accessible
 The public getx method defined in class A
Class C
now becomes protected in class B. This has Inherits all public &
CLICK TO EDIT MASTER TITLE STYLE
significance while accessing the getx
method from a code that is defined outside
protected members of
Class A and Class B as
public & protected Not accessible
the subclasses of class B. respectively.

Ouside Code
Not accessible

B ObjectB;
int x=ObjectB.getx();
C ObjectC;
int y = ObjctC.getx();
Protected inheritance

16
TYPES OF INHERITANCE
Class A
 If we define main method as follows, the call private
to getx method would be illegal.
protected

public
Protected inheritance from
class B
Class B
private

protected

public
 However, if we derive another class from Inherits all protected
members of Class A as
class B as shown in the above diagram, the protected & public as
getx method would be visible within the protected

definition of the newly derived class. The Public inheritance from class C
Not accessible
following derivation is valid:
Class C
Inherits all public &
CLICK TO EDIT MASTER TITLE STYLE protected members of
Class A and Class B as
public & protected Not accessible
respectively.

Ouside Code
Not accessible

B ObjectB;
int x=ObjectB.getx();
C ObjectC;
int y = ObjctC.getx();
Protected inheritance

GRANTING ACCESS TO BASE CLASS MEMBER IN DERIVED CLASS

CLICK TO EDIT MASTER TITLE STYLE

17
CALLING SEQUENCE FOR CONSTRUCTORS & DESTRUCTORS
 Whenever we create an object of a derived class, the runtime creates an object of its
immediate super class and all its super classes up the hierarchy up to the object of the
base class.
 Thus, if class A is the base class and class B derives from A, class C derives from B, and
class D derives from C, whenever we create an object of class D, the program will
create object of class C, class B and class A.
 During the object creation process, the respective class constructors are called.
 Now we will discuss the order of calling the class constructors and destructors during
object creation.
 Consider the following definition for our base class:

CLICK TO EDIT MASTER TITLE STYLE

CALLING SEQUENCE FOR CONSTRUCTORS & DESTRUCTORS


 The BaseClass defines a no-argument constructor and a destructor.
 Both methods print a message on the user console whenever they are called.
 We can derive a class from this base class and write constructor and destructor as
follows:

CLICK TO EDIT MASTER TITLE STYLE


 The child class constructor and destructor both print a message on the user console
whenever they are called.
 As the child class inherits from the base class, whenever we create an object of child
class, the runtime first creates an object of base class.

18
CALLING SEQUENCE FOR CONSTRUCTORS & DESTRUCTORS
 Similarly, whenever the object of child class is destroyed, the runtime destroys the
child object first and then the base class object.
 To test this, we write a main method and create an object of child class as follows:

 If we run this program, we will get the following output on the console.

CLICK TO EDIT MASTER TITLE STYLE


 Note that the base class constructor is called first followed by the subclass
constructor. Thus, the runtime creates an object of base class first and then creates an
object of child class on top of it.
 Similarly, during the subclass object destruction process, the destructor for the child
class gets called before the destructor for the base class.

CALLING SEQUENCE FOR CONSTRUCTORS & DESTRUCTORS


 The class hierarchy may now be extended further by deriving another class from class
B. Such a declaration is shown below:

 Now, if we create an object of SecondChild class, the runtime will first construct the
object of the base class, followed by the object of the FirstChild class and finally
the object of the SecondChild class.
CLICK TO EDIT MASTER TITLE STYLE

19
CALLING SEQUENCE FOR CONSTRUCTORS & DESTRUCTORS
 Similarly, whenever the program destroys the object of SecondChild class, the
destructor for SecondChild class is called first, followed by the destructor of the
FirstChild class and finally the destructor for base class. This is easily verified using
the following main function.

 When we run the above main program, we will see the following output on the
console:

CLICK TO EDIT MASTER TITLE STYLE

CALLING SEQUENCE FOR CONSTRUCTORS & DESTRUCTORS

CLICK TO EDIT MASTER TITLE STYLE

20
Parameter Passing To Superclass Constructors
 We have seen the order in which constructors and destructors are called during the
creation of a subclass object.
 We will now study how to pass the parameters to the superclass constructors during
the object creation process.
 Consider the following class definition:

CLICK TO EDIT MASTER TITLE STYLE


 Class A defines one private member of type integer. This class defines a constructor
that takes a single parameter of type integer and initializes the data member a using
the received parameter.
 The utility method dumpA prints the value of the data member on the user console.

Parameter Passing To Superclass Constructors


 We will now derive a class from class A as follows:
class B: public A
{
int b;

 We have also declared a private data member called b of type integer in the class
definition.
 We will now write the class constructor. Note that the class constructor will
automatically call the constructor of its superclass, that is, of class A.
 The class A constructor requires a parameter of type integer.
 Now, how do we declare a constructor for class B?
 The declaration should be as follows:
CLICK TO EDIT MASTER TITLE STYLE
B(int a1):A(a1)
 The class constructor receives one parameter of type integer and passes its value to
its super class constructor.

21
Parameter Passing To Superclass Constructors
 If class B requires another parameter to initialize its data member, we will modify the
constructor declaration as follows:
B(int b1,int a1):A(a1)

 Here, the first parameter b1 may be used for initializing the data member of class B
and the second parameter, as before, is passed on to the constructor of class A.
 The complete constructor of class B may now take the following form:
B(int b1,int a1):A(a1)
{
b=b1;
} CLICK TO EDIT MASTER TITLE STYLE
 The parameter b1 is used for initializing the data member b. The parameter a1 is
passed to the constructor of class A.

Parameter Passing To Superclass Constructors

CLICK TO EDIT MASTER TITLE STYLE

22

You might also like