You are on page 1of 14

1|Page

Inheritance- Module 4
Unit 4: (10 hrs.) Inheritance: Inheritance - Defining derived classes-Visibility
modes-Single, Multilevel, Multiple, Hierarchical and Hybrid inheritance- Virtual base
classes- Abstract classes- Constructors in derived classes- Nesting of classes.

Inheritance is one of the important features of OOP .Inheritance is the method by which objects
of one class acquires the properties of another class.

 expresses an “is-a“ relation


 Creates a relation between different classes
 New classes created from existing classes
 reuse the code functionality
 fast implementation time.
 The new class(derived class) inherits all the member variables and functions of the base
class

Inheritance: Extending Classes

The mechanism of deriving a new class from an old one is called inheritance (or derivation).The
old class is referred to as base class.A base class is a previously defined class that is used to
define new classes.The new class is called the derived class or subclass.A derived class inherits
all the data and function members of a base class (in addition to its explicitly declared members.)
The derived class inherits some or all of the traits from the base class.A class can also inherit
properties from more than one class or from more than one level .

 In inheritance, some of the base class data elements and member functions are
inherited into the derived class.
 We can add our own data and member functions for extending the functionality of the
base class.
 It is a powerful tool for incremental program development.
 Can increase the capabilities of an existing class without modifying it.

Types of Inheritance

 Single Inheritance
o A derived class with only one base class.
2|Page

 Multiple Inheritance
o A derived class with several base classes.
 Hierarchical Inheritance
o A traits of one class may be inherited by more than one class.
 Multilevel Inheritance
o The mechanism of deriving a class from another derived class.
 Hybrid Inheritance
o The mechanism of deriving a class by using a mixture of different methods.

Base and Derived Classes -Defining Derived Classes

A derived class can be defined by specifying its relationship with the base class in addition to its
own details.
Syntax:-
class derived-class-name : visibility-mode base-class-name
{
………//
………// 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.

Derived Classes-Private Derivation

When a base class is privately derived by a derived class, “public members” of the base class
become “private members” of the derived class.Therefore the members of the derived class can
only access the public members of the base class.They are inaccessible to the objects of the
derived class.No member of the base class is accessible to the objects of the derived class.

Derived Classes-Public Derivation


3|Page

When a base class is publicly inherited, ”public members” of the base class become the “public
members” of the derived class.They are accessible to the objects of the derived class.The private
members of the base class are not inherited in both the cases (publicly/privately inherited).The
private members of a base class will never become the members of its derived class.

Private Inheritance:It is the inheritance facilitated by private visibility mode.In private


inheritance ,the protected and public members of base class become private members of the
derived class.

Public Inheritance:It is the inheritance facilitated by public visibility mode.In public


inheritance ,the protected  members of base class become protected members of the derived
class and public members of the base class become public members of derived class.;

Protected Inheritance:It is the inheritance facilitated by protected visibility mode.In protected


inheritance ,the protected and public members of base class become protected members of the
derived class.

What a derived class can add


 New data members
 New member functions (also overwrite existing ones)
 New constructors and destructor

What a derived class doesn't inherit


 The base class's constructors and destructor
Making a Private Member Inheritable

By making the visibility limit of the private members to the public.The visibility modifier
“protected” can be used for this purpose.A member declared as “protected” is accessible by the
member functions within its class and any class immediately derived from it.It can not be
accessed by the functions outside these two classes.

class alpha

private : // optional

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

………

protected :

……… // visible to member functions

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

public :

……… // visible to all functions

……… // in the program

};

Protected Member
4|Page

When a protected member is inherited in public mode, it becomes protected in the derived
class.They are accessible by the member functions of the derived class.And they are ready for
further inheritance.When a protected member is inherited in private mode, it becomes private
in the derived class.They are accessible by the member functions of the derived class.But, they
are not available for further inheritance.

Protected Derivation

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


derivation, both the public and protected members of the base class become protected
members of the derived class.

Access Control to Data Members

Functions that can have access to the private and protected members of a class:

 A function that is a friend of the class.


 A member function of a class that is a friend of the class.
 A member function of a derived class.
5|Page

Single inheritance

This is the very simple type of inheritance. In this type, One derived class inherits from one
base class.

Example: Refer Your record Example

Multilevel Inheritance:

C++ also provides the facility of multilevel inheritance, according to which the derived class can
also be derived by an another class, which in turn can further be inherited by another and so on.
The class A serves as a base class for the derived class B, which in turn serves as a base class for
the derived class C.Class B provides a link for the inheritance between A and C.The chain ABC is
known as inheritance path.

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


6|Page

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

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

Example: Refer Your record Example

Multiple Inheritance

A class can inherit the attributes of two or more classes.Multiple inheritance allows us to
combine the features of several existing classes as a starting point for defining new classes.It is
like a child inheriting the physical features of one parent and the intelligence of another.
Multiple inheritance is achieved whenever more than one class acts as base classes for other
classes. This makes the members of the base classes accessible in the derived class, resulting in
better integration and broader re-usability.

Example: Refer Your Notebook Example

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

………

……… (Body of D)

………

};
7|Page

Where, visibility may be either public or private.

The base classes are separated by comma.

Hierarchical Inheritance

Inheritance support hierarchical design of a program. Additional members are added through
inheritance to extend the capabilities of a class. Programming problems can be cast into a
hierarchy where certain features of one level are shared by many others below that level. When
two or more classes are derived from a single base class, then Inheritance is called the
hierarchical inheritance

Example: Refer Your Notebook Example

Hybrid Inheritance

Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.

Example: Refer Your Notebook Example

Virtual Base Classes


Here the result class has two direct base classes test and sports which themselves have a
common base class student.The result inherits the traits of student via two separate paths.It can
also inherit directly as shown by the broken line.The student class is referred to as indirect base
class.
8|Page

All the public and protected members of student are inherited into result twice, first via Exams
and again via sports.This means result class have duplicate set of members inherited from
student.

class student
{
………
};
class test : virtual public student
{
………
};
class sports : public virtual student
{
………
};
class result : public test, public sports
{
………\
};
Virtual base class-example

class student
{
    protected: int roll_no;
    
    public: void get_no(int x)
    {
        roll_no=x;
    }
    
    void put_no()
    {
        cout<<"Roll Number:"<<roll_no;
    }
};
 
class test: virtual public student
{
    protected: float sub_marks;
    
    public: void get_submarks(float y)
    {
9|Page

        sub_marks=y;
    }
    
    void put_submarks()
    {
        cout<<"\nSubject Marks:"<<sub_marks;
    }
};
class sports: public virtual student
{
    protected: float sp_marks;
    
    public: void get_spmarks(float z)
    {
        sp_marks=z;
    }
    
    void put_spmarks()
    {
        cout<<"\nSports Marks:"<<sp_marks;
    }
};
 
class result: public test, public sports
{
    float total_marks;
    
    public: void put_result()
    {
        total_marks=sub_marks+sp_marks;
        put_no();
        put_submarks();
        put_spmarks();
        cout<<"\nTotal Marks:"<<total_marks;
    }
};
int main()
{
    result R;
    
    R.get_no(20);
    R.get_submarks(75.6);
    R.get_spmarks(81.2);
    R.put_result();
    return 0;
}

In the above example student class is an abstract class, as it is


not used to create an object. It is used only for deriving other
classes.

Constructors in Derived Classes

If no base class constructor takes any arguments, the derived class need not have a constructor
function.If any base class contains a constructor with one or more arguments, then it is
mandatory for the derived class to have a constructor and pass the arguments to the base class
constructors.When both the derived and base class contain constructors, the base constructor is
executed first and then the constructor in the derived class is executed.In case of multiple
inheritance, the base class constructors are executed in the order in which they appear in the
declaration of the derived class.In a multilevel inheritance, the constructors will be executed in
10 | P a g e

the order of inheritance.Since the derived class takes the responsibility of supplying initial values
to its base classes, we supply the initial values that are required by all the classes together, when
a derived class object is declared.

The constructor of the derived class receives the entire list of values as its arguments and
passes them on to the base constructors in the order in which they are declared in the derived
class.The base constructors are called and executed before executing the statements in the body
of the derived constructor.

The header line of derived-constructor function contains two parts separated by a colon (:).

The first part provides the declaration of the arguments that are passed to the derived
constructor.

The second part lists the function calls to the base constructors.

Defining Derived Constructors

Derived-constructor(Arglist1, Arglist2, … ArglistN, ArglistD) :

base1(arglist1),

base2(arglist2),

baseN(arglistN)

Example: Refer Your record program Example

Member Classes : Nesting of Classes

A nested class is a class that is declared in another class. The nested class is also a member variable
of the enclosing class and has the same access rights as the other members. However, the member
functions of the enclosing class have no special access to the members of a nested class.
A program that demonstrates nested classes in C++ is as follows.

class A {
   public:
   class B {
      private:
      int num;
      public:
      void getdata(int n) {
         num = n;
      }
      void putdata() {
         cout<<"The number is "<<num;
      }
11 | P a g e

   };
};
int main() {
   cout<<"Nested classes in C++"<< endl;
   A :: B obj;
   obj.getdata(9);
   obj.putdata();
   return 0;
}

Virtual Functions

 Polymorphism refers to the property by which objects belonging to different classes are
able to respond to the same message, but in different forms.
 An essential requirement of polymorphism is therefore the ability to refer to objects
without any regard to their classes.
 This necessitates the use of a single pointer variable to refer to the objects of different
classes.
 We use pointer to base class to refer to all the derived objects.
 When we use the same function name in both the base and derived classes, the function
in base class is declared as virtual using the keyword virtual preceding its normal
declaration.
 When a function made virtual, C++ determines which function to use at run time based
on the type of object pointed to by the base pointer, rather than the type of the pointer.
 One important point to remember is that, we must access virtual functions through the
use of a pointer declared as a pointer to the base class.
 Run time polymorphism is achieved only when a virtual function is accessed through a
pointer to the base class.
Example: Virtual Functions
Example1
#include <iostream.h>
class Bclass
{
public:
virtual void disp() { cout << " BASE BASE\n" ; }
virtual void sh() { cout << "base base\n"; }
};
class Dclass : public Bclass
{
public:
void disp() { cout << "DERIVED DERIVED\n"; }
void sh() { cout << "derived derived\n"; }
};
int main()
12 | P a g e

{
Bclass B;
Dclass D;
Bclass *ptr;
cout << "ptr points to base class\n" ;
ptr = &B;
ptr->disp();
ptr->sh();
cout << "ptr points derived class\n";
ptr = &D;
ptr->disp();
ptr->sh();
return 0;
}

Example2
#include<iostream.h>
#include<conio.h>
class base
{
public:
virtual void show()
{
cout<<"\n  Base class show:";
}
void display()
{
cout<<"\n  Base class display:" ;
}
};

class derive:public base


{
public:
void display()
{
cout<<"\n  Drive class display:";
}
void show()
{
cout<<"\n  Drive class show:";
}
};

void main()
{
clrscr();
base obj1;
base *p;
cout<<"\n\t P points to base:\n"  ;
p=&obj1;
13 | P a g e

p->display();
p->show();
cout<<"\n\n\t P points to drive:\n";
derive obj2;
p=&obj2;
p->display();
p->show();
getch();
}

Rules for Virtual Functions


 The virtual functions must be members of some class.
 They cannot be static members.
 They are accessed by using object pointers.
 A virtual function can be a friend of another class.
 A virtual function in a base class must be defined, even though it may not be used.
Pure Virtual Functions
 A pure virtual function is a function declared in a base class that has no definition relative to
the base class.
 A do-nothing function may be defined as follows:
o virtual void display( ) = 0;
 A class containing pure virtual functions cannot be used to declare any objects of its own. –
abstract classes.
 The main objective of an abstract base class is to provide some traits to the derived classes
and to create a base pointer required for achieving run time polymorphism.
Example: Pure virtual Functions / Abstract Class
class Shape
{
public:
virtual void Draw() = 0; // pure virtual function
};
class Line : public Shape
{
public:
//override interface function
void Draw() // also virtual in derived class
{
cout << “Line is being drawn”;
// …
}
};
void main()
{
// Shape obj; // error as Shape class is abstract
Line lineObj; // creating a derived class object
Shape* ptr; // creating a base class pointer

ptr = &linedObj; // assigning address of derived class // object to


base class pointer
ptr->Draw(); // derived class draw() will be called
}
14 | P a g e

Abstract Classes
An abstract class is one that is not used to create objects.An abstract class is designed only to act
as a base class.It is a design concept in program development and provides a base upon which
other classes may be built.

An abstract class is a class that is designed to be specifically used as a base class. An abstract class
contains at least one pure virtual function. You declare a pure virtual function by using a pure
specifier (= 0) in the declaration of a virtual member function in the class declaration.
The following is an example of an abstract class:

class AB {
public:
virtual void f() = 0;
};

You might also like