0% found this document useful (0 votes)
197 views9 pages

CHAPTER 8: Inheritance

This document discusses inheritance in C++. It defines inheritance as objects of one class acquiring properties of another class, supporting hierarchical classification. There are different types of inheritance including single inheritance where one class inherits from one base class, multiple inheritance where a class inherits from multiple base classes, and multilevel inheritance where a class inherits from another derived class. The document provides examples of single inheritance with a stack class and derived stack1 class, and multilevel inheritance with student, test, and result classes. It also discusses visibility of inherited members and the general forms of single and multiple inheritance.

Uploaded by

darshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
197 views9 pages

CHAPTER 8: Inheritance

This document discusses inheritance in C++. It defines inheritance as objects of one class acquiring properties of another class, supporting hierarchical classification. There are different types of inheritance including single inheritance where one class inherits from one base class, multiple inheritance where a class inherits from multiple base classes, and multilevel inheritance where a class inherits from another derived class. The document provides examples of single inheritance with a stack class and derived stack1 class, and multilevel inheritance with student, test, and result classes. It also discusses visibility of inherited members and the general forms of single and multiple inheritance.

Uploaded by

darshan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 9

C++

CHAPTER 8: Inheritance

Introduction:
 Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
 It supports the concept of hierarchical classification.
 e.g. “Canine” is derived from the class “Mammal” which is again derived from the class
“Animal”. (See figure 6 of Chapter 1)
 Each derived class shares common characteristics with the class from which it is derived.
 The mechanism of deriving a new class from an old one is called inheritance (or derivation).
 The old class is referred to as the base class and the new one is called the derived class or
subclass.
 The new class will have the combined features of both the classes.
 It provides reusability.
 We can add additional features to an existing class without modifying the base class when we
derive a new class from the base class.
 Allows the programmer
o To reuse a class
o To tailor the class in such a way that it does not introduce any undesirable side-effects
into the rest of the classes.

The General Form of Inheritance:


class derived-class-name : derived-class-visibility-mode base-class-name
{
// members of derived class.
};

Examples:
(1) Private Derivation (2) Public Derivation (3) Private Derivation
(By Default)
class circle: private shape class circle: public shape class circle: shape
{ { {
Members of circle members of circle members of circle
}; }; };

(4) Protected Derivation


class circle: protected shape Here, shape is a base class, while circle is the derived class
{ from the base class shape.
Members of Circle
};

protected (making private member inheritable):

Till now, we have seen that we declare the members as either private or public. We know that
private variables are not accessible outside the class (such as main( ) ) while public members can be
accessed easily outside the class. What do we do if the private data needs to be inherited by a
derived class? C++ asks us to declare those variables or functions to be declared as protected. A
member declared as protected is accessible by the member functions within its class and any class
immediately derived from it. Thus class can have now, three visibility-modes i.e. private,
protected and public. (See material of Chapter 5: Class Specification (page 2))

By Darshit Shah Page 1 of 9


C++

Visibility of Inherited Members:

Refer to the following table to see the effects of Inheritance of base-class-members in derived-
class.
Base Class Derived Class Visibility
Visibility Public Derivation Private Derivation Protected Derivation
Private  Not Inherited Not Inherited Not Inherited
Protected  Protected Private Protected
Public  Public Private Protected

Different Forms of Inheritance:


There are five forms of inheritance as explained below.

A A B A A A

B C B C D B B C

Single Multiple Hierarchical


C D

Multilevel Hybrid
Single Inheritance: Only one derived class from a single base class.
Multiple Inheritance: One derived class from several base classes.
Hierarchical Inheritance: Several Derived class from one base class.
Multilevel Inheritance: Deriving a class from another ‘derived-class’.
Hybrid Inheritance: Combination of different types of Inheritance.

Example of Single Level Inheritance:


#include <iostream.h>
#include <stdio.h>
#include <conio.h>
const int MAX = 5;
class stack
{
protected:
int top, s[MAX];
public:
stack()
{
top = -1;
}
void push(int num)
{
top++;
s[top] = num;
cout << "s[" << top << "] = " << num << endl;
}
int pop()
{
int num;
num = s[top];
top --;
return num;
}

By Darshit Shah Page 2 of 9


C++
};
class stack1: public stack
{
public:
void push(int num)
{
if ( top == MAX - 1)
cout << "Stack is full" << endl;
else
stack::push(num);
}
int pop()
{
int n;
if(top == -1)
{
cout << "Stack is empty." << endl;
return NULL;
}
else
{
n = stack::pop();
return n;
}
}
};

void main()
{
clrscr();
int n;
stack1 stk;
stk.push(10); stk.push(20); stk.push(30); stk.push(40);
stk.push(50); stk.push(60); stk.push(70); stk.push(80);
n = stk.pop();
cout << "Value : " << n << " has been popped." << endl;
n = stk.pop();
cout << "Value : " << n << " has been popped." << endl;
getch();
};
Inherit1.cpp

Q.1. What will be the output of the above program?


Q.2. What would be the output, if object stk is created from class stack instead of class stack1?
Q.3. If we change MAX to 10, what would be the output?
Q.4. Here, both classes have functions having common name. Which function would be executed
first?

Example of Multilevel Inheritance:


#include <iostream.h>
#include <stdio.h>
#include <conio.h>

class student
{
protected:
int rn;
public:
void get_rn(int);
void put_rn(void);
};

By Darshit Shah Page 3 of 9


C++

class test : public student


{
protected:
int english,cp;
public:
void get_marks(int,int);
void put_marks(void);
};

class RESULT : public test


{
private:
int total;
public:
void display(void);
};

void student::get_rn(int rollno)


{
rn = rollno;
}
void student::put_rn(void)
{
cout << "Roll No. = " << rn << endl;
}

void test::get_marks(int e,int c)


{
english = e;
cp = c;
};
void test::put_marks(void)
{
cout << "Marks in English = " << english << endl;
cout << "Marks in Computer = " << cp << endl;
};

void RESULT::display(void)
{
total = english + cp;
put_rn();
put_marks();
cout << "Total = " << total << endl;
};

void main()
{
RESULT s10;
s10.get_rn(10);
s10.get_marks(80,85);
s10.display();
};
Inherit2.cpp
Multiple Inheritance:
 It 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.
 The derived class will contain all the members of all base-classes in addition to its own
members.

By Darshit Shah Page 4 of 9


C++

The General Form of Multiple Inheritance:


class dc : dc-visibility-mode base-class-name1 , dc-visibility-mode base-class-name2 , …
{
// members of derived class.
};

// multiple inheritance
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>

class father
{
private:
char f_name[50];
char f_blood_grp[5];
int f_height_in_feet;
int f_height_in_inch;
public:
void f_init(char * nm, char * bg, int hf, int hi)
{
strcpy(f_name,nm);
strcpy(f_blood_grp,bg);
f_height_in_feet = hf;
f_height_in_inch = hi;
};
void f_display(void)
{
cout << "Name of father = " << f_name << endl;
cout << "Blood Group of father = " << f_blood_grp << endl;
cout << "Height = " << f_height_in_feet <<
" Feet & " << f_height_in_inch << " Inches " << endl;
}
};
class mother
{
private:
char m_name[50];
char m_blood_grp[5];
int m_height_in_feet;
int m_height_in_inch;
public:
void m_init(char * nm, char * bg, int hf, int hi)
{
strcpy(m_name,nm);
strcpy(m_blood_grp,bg);
m_height_in_feet = hf;
m_height_in_inch = hi;
};
void m_display(void)
{
cout << "Name of Mother = " << m_name << endl;
cout << "Blood Group of Mother = " << m_blood_grp << endl;
cout << "Height = " << m_height_in_feet <<
" Feet & " << m_height_in_inch << " Inches " << endl;
}
};

By Darshit Shah Page 5 of 9


C++

class child : public father, public mother


{
private:
char c_name[50];
char c_blood_grp[5];
int c_height_in_feet;
int c_height_in_inch;
public:
void c_init(char * nm, char * bg, int hf, int hi)
{
strcpy(c_name,nm);
strcpy(c_blood_grp,bg);
c_height_in_feet = hf;
c_height_in_inch = hi;
};
void c_display(void)
{
f_display();
m_display();
cout << "Name of Child = " << c_name << endl;
cout << "Blood Group of Child = " << c_blood_grp << endl;
cout << "Height = " << c_height_in_feet <<
" Feet & " << c_height_in_inch << " Inches " << endl;
}
};

void main()
{
clrscr();
child c1;
c1.f_init("Darshit","O+",5,10);
c1.m_init("Ragi","A+",5,7);
c1.c_init("Aashna","O+",5,7);
c1.c_display();
getch();
};
Inherit3.cpp
Ambiguity Resolution in Inheritance:
 What happens, if same function name appears in different base classes from where we derive
another class?
Answer:
 Use class resolution operator to invoke function of specific class.

Let us replace the name of the functions in the above program as under
Replace f_init(), m_init() & c_init() with init().
Replace f_display(), m_display() & c_display() with display().
In this case, we will have to change 1st two lines of display() function in child class and main( ) as
under.
Father::display();
Mother::display();
void main()
{
clrscr();
child c1;
c1.father::init("Darshit","O+",5,10);
c1.mother::init("Ragi","A+",5,7);
c1.init("Aashna","O+",5,7);
c1.display();
getch();
By Darshit Shah Page 6 of 9
C++

};
Hierarchical Inheritance:
Many times it happens that certain features of one level are shared by many others below that level.
e.g. all the students have certain things in common like roll no, name, address, date of birth but they
belong to different streams like engineering, medical or art. Again engineering students may be
classified further as mechanical, electrical or civil & so on. Here we use hierarchical inheritance.
We can construct one base class called students having common features from which we can derive
another classes called engineering, medical or art. From class engineering, we can derive another
classes called mechanical, electrical or civil. The syntax for deriving the class is same as that of
single inheritance. Remember, while common things will be put in base class, different derived
classes can have their own features unique to the derived classes. E.g. subjects in different
branches are totally different.

Hybrid Inheritance:
Here, we derive classes from different types of inheritance e.g. combining multiple inheritance with
hierarchical or combining multilevel with multiple inheritance, etc. We have to follow the
respective syntax for deriving the different classes.

Virtual Base Classes:


When we try to combine different types of inheritance (hybrid), there may be situations whereby a
derived class inherits the traits of base class twice through different classes derived from base class.
E.g. From class ‘grandparent’ we derive two classes called ‘father’ and ‘mother’. From class
‘father’ & ‘mother’, we derive another base class called ‘child’. Thus ‘child’ class will inherit the
properties of ‘grandparent’ class via two different classes viz. ‘father’ and ‘mother’. This
introduces ambiguity and should be avoided by declaring the common base class as virtual base
class as shown below.

class grandparent
{

};
class father : virtual public grandparent
{

};
class mother : public virtual grandparent
{

};
class child : public father, public mother
{

};
When a base class is made virtual, C++ takes necessary care to see that only one copy of that class
is inherited, regardless of how many inheritance paths exist between the virtual base class and a
derived class. The keyword virtual and public may be used in either order.

Constructors in Derived Classes:


 We know that we use constructors for initializing the objects.
 There may or may not be constructors in base class or derived classes.
 These constructors may or may not have arguments.
Refer to the following table to decide whether the constructor is required in derived class or not.
Base Class No. of Arguments Derived class
Constructor in base class constructor Constructors
Absent N.A. May or may not have Constructor
Present Zero May or may not have Constructor
By Darshit Shah Page 7 of 9
C++

Present > Zero Must have Constructor.


The General Form of Defining a Derived Constructor:
Derived-Constructor (ArglistD):BC1(Arglist1),BC2(arglist2),…BCN(arglistN)
{
// Body of Constructor
}
Here, ArglistD refers to the arguments of the derived constructor, while Arglist1 to ArglistN refers
to the arguments of base class constructors and BC1 to BCN are the name of the constructors of
Base classes.

Passing Arguments to the Constructor:


 Derived class is responsible for supplying initial values to its base class.
 When we create objects from derived class, we supply all values to derived class constructor
that in turn will pass to the base constructors in the order in which they are declared in the
derived class.
Look at the following program.

#include <iostream.h>
#include <stdio.h>
#include <conio.h>
class bc
{
public:
bc(char * obj)
{
cout << obj << "Base Class Constructor" << endl;
}
};
class dc:public bc
{
public:
dc(char * obj):bc(obj)
{
cout << obj << "Derived Class Constructor." << endl;
}
};
void main()
{
clrscr();
dc b1("b1->");
getch();
};
Inherit4.cpp
Output:
B1->Base Class Constructor
B1->Derived Class Constructor

Order of Execution of Constructor Functions:


 When both classes contain constructors, the base constructor is executed first and then the
derived class constructor will be executed.
 In case of multiple inheritance, the base classes are constructed in the order in which they
appear in the declaration of the derived class.
 In case of multilevel inheritance, the constructors will be executed in the order of inheritance.
 Virtual base class constructors are always invoked first.
E.g.
class B : public A { }; à A() , B()
class A : public B, public C { }; à B( ) , C( ), A( )
class A : public B, virtual public C { }; à C( ) , B( ), A( )
By Darshit Shah Page 8 of 9
C++

By Darshit Shah Page 9 of 9

You might also like