Вы находитесь на странице: 1из 72

INHERITANCE

PDPU
Inheritance…
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. The bird “sparrow” is a part of the class “flying
bird” which is again a part of the class “bird”.

2
Inheritance…
Each derived class shares common characteristics
with the class from which it is derived.
It provides reusability.
We can add additional features to an existing class
without modifying it when we derive a new class
from existing one.

3
Inheritance…
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.

4
Inheritance…
The new class will have the combined features of
both the classes.
Allows the programmer
To reuse a class
To tailor the class in such a way that it does
not introduce any undesirable side-effects
into the rest of the classes.

5
Different Types of Inheritance…
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance

6
Single Inheritance…
A derived class with only one base class is called
Single Inheritance.

7
Multilevel Inheritance…
A class is derived from another derived class is
known as multilevel inheritance.

C 8
Multiple Inheritance…
A derived class from several base classes is called
multiple inheritance.

A B

9
Hierarchical Inheritance…
Features of one class can be inherited by more
than one class is known as hierarchical
inheritance.

B C
10
Hybrid Inheritance…
Combination of different types of inheritance is
known as hybrid inheritance.

B C

D 11
Defining Derived Classes…
General Form…

class derived-class name : visibility-mode base-class-name


{
… members of derived class

}
Here,
:  derived-class name is derived from base-class-
name.
visibility-mode is optional. It can be either
private, public or protected. By default, it is private.
12
Defining Derived Classes …
Features Of Base Class …

Visibility mode specifies whether


The feature of the base class are privately derived
or publicly derived.
Example
Class ABC: public XYZ
{
Members of abc
};

13
Defining Derived Classes …
Features Of Base Class …

class ABC: private XYZ


{
MEMBERS OF ABC
};
class ABC: XYZ // Privately Inherited
{
MEMBERS OF ABC
};

14
Defining Derived Classes …
Features Of Base Class …

class ABC: protected XYZ // Protected derivation


{
MEMBERS OF ABC
};
This form is used rarely.

15
Example…
Function Main ( )…

index1 i;
index j;
j++;
cout << "j."; j.display();
i++; i++;
cout << "i."; i.display();
i--;
cout << "i."; i.display();

Please go through
the program
“inherit1.cpp”
16
Example…
Defining Class Index…

class index // base class


{
protected:
int count;
public:
index()
{
count = 0;
}

17
Example…
Defining Class Index…

index (int c)
{
count = c;
}
void display()
{
cout << "count = " << count << endl;
}

18
Example…
Defining Class Index…

void operator ++ (int)


{
count++;
}
};

19
Example…
Deriving Class Index1…

class index1: public index // derived class


{
public:
void operator -- (int)
{
count--;
}
};

GENERAL FORM
20
Example…
Function Main ( ) & Output …

index1 i; OUTPUT
index j;
j++;
cout << "j."; j.display(); j.count = 1
i++; i++;
cout << "i."; i.display();
i.count = 2
i--;
cout << "i."; i.display();
i.count = 1
Please go through
the program
“inherit1.cpp”
21
protected: instead of private:
why? …

Can member functions of the derived class access


members of the base class?

Can operator – – (int) in index1 access count in


index?

22
protected: instead of private:
Answer …

Members of a derived class can access members of


the base class only if the base class members are
public or protected.
They can’t access private members.
We can’t make them public as they can be accessed
from anywhere in the program and thus not good
for data hiding.

23
protected: instead of private:
Answer …

A protected member can be accessed by member


functions in its own class or in any class derived
from its own class.
It can’t be accessed from functions outside these
classes, such as main().
They behave just like private members until a new
class is derived from the base class that has
protected members.

24
FEW POINTS…
We can increase the functionality of the base class
(index) without modifying it through the derived
class (index1).
Inheritance does not work in reverse as the base
class & its objects have no knowledge about any
classes derived from the base class.

25
Try the following…
In class index, declare variable count as private
instead of protected.
Change visibility mode specifier to private instead
of public
(write class index1: private index
instead of class index1: public index)
Call j--; from main.

26
EXAMPLE 2 …Function main ( ) …
int n;
stack1 stk;
stk.push(10); stk.push(20); stk.push(30);
stk.push(40); stk.push(50);

n = stk.pop();
cout << "Value : " << n << " popped.“;
n = stk.pop();
cout << "Value : " << n << " popped.“;
getch();
27
EXAMPLE 2 … Defining class stack…

const int MAX = 25;


class stack
{
protected:
int s[MAX], top;
public:
stack()
{
top = -1;
} Please go through
the program
“inherit2.cpp”
28
EXAMPLE 2 … Defining class stack…

void push (int num) int pop()


{ {
top++; int num;
s [top] = num; num = s[top];
}
top --;
return num;
}

}; // end of class stack.


29
EXAMPLE 2 …
Inheriting class stack1 from stack …

class stack1: public stack


{
public:
void push ( int num)
{
if ( top == MAX - 1)
cout << "Stack is full" << endl;
else
stack::push(num);
}
30
EXAMPLE 2 …
Inheriting class stack1 from stack …

int pop()
{
int n;
if (top == -1)
{
cout << "Stack is empty." ;
return NULL;
}

31
EXAMPLE 2 …
Inheriting class stack1 from stack …

else
{
n = stack::pop();
return n;
}
}
};

32
EXAMPLE 2 …
What is happening? …

s[0] = 10  now change the


s[1] = 20 value of MAX to 3
s[2] = 30 and run the program.
s[3] = 40  Create object stk
s[4] = 50 from stack class and
value : 50 popped run the program.
value : 40 popped

33
Few points…
Here, both classes stack1 and stack have common
functions.
Which one would be executed?
The function in the derived class gets a priority
when the function is called as a member of the
derived class object.
A program can declare objects of both the base
and derived classes. The two objects are
independent of one another.
34
Few Points…
Friend function can access private as well as
protected data directly,
The member functions of a derived class can
access only the protected data.

35
Visibility Of Inherited Members…
BASE DERIVED CLASS VISIBILITY
CLASS
VISIBILITY PUBLIC PRIVATE PROTECTED
DERIVATION DERIVATION DERIVATION

PRIVATE NOT NOT NOT


INHERITED INHERITED INHERITED
PROTECTED PROTECTED PRIVATE PROTECTED

PUBLIC PUBLIC PRIVATE PROTECTED


36 “inherit3.cpp”
Multilevel Inheritance…

BASE CLASS STUDENT GRAND FATHER

INTERMEDIATE
BASE CLASS TEST FATHER

DERIVED CHILD
CLASS RESULT
Please go through
the program
“inherit4.cpp”
37
Multilevel Inheritance…
Class Declaration …
class student { … };
class test : public student { … };
class result : public test { … };

38
Multilevel Inheritance…
Student Class Declaration …

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

39
Multilevel Inheritance…
student class declaration …

void student::get_rn(int rollno)


{
rn = rollno;
}

void student::put_rn(void)
{
cout << "Roll No. = " << rn << endl;
}
40
Multilevel Inheritance…
test class declaration …

class test : public student


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

41
Multilevel Inheritance…
test class declaration …

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;
}; 42
Multilevel Inheritance…
result class declaration …

class RESULT : public test


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

43
Multilevel Inheritance…
result class declaration …

void RESULT :: display (void)


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

44
Multilevel Inheritance…
What result class will have …

private:
int total;
protected:
int rn, english, cp;
public:
void get_rn (int);
void put_rn (void);
void get_marks( int , int);
void put_marks (void);
void display (void); 45
Multilevel Inheritance…
main() function …

void main()
{
clrscr();
RESULT s10;
s10.get_rn(10);
s10.get_marks(80,85);
s10.display();
getch();
};
46
Multiple Inheritance…
A derived class from several base classes is called
multiple inheritance.

A B

47
Syntax Of Derived Class With Multiple Base
Classes…

class D : visibility BC-1, visibility BC-2


{

… body of D.
};
Here, D  Derived Class,
BC1 base-class-1 &
BC2 base-class-2

48
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.

49
Multiple Inheritance…
Example…
class father
{
private:
char f_name[50];
char f_blood_grp[5];
int f_height_in_feet;
int f_height_in_inch;

50
Multiple Inheritance…
Example…
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;
};

51
Multiple Inheritance…
Example…
void f_display(void)
{
cout << "Name of father = " << f_name;
cout << "Blood Group = " << f_blood_grp;
cout << "Height = "
<< f_height_in_feet << " Feet & "
<< f_height_in_inch << " Inches ";
}
};
52
Multiple Inheritance…
Example…
class mother
{
private:
char m_name[50];
char m_blood_grp[5];
int m_height_in_feet;
int m_height_in_inch;

53
Multiple Inheritance…
Example…
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;
};

54
Multiple Inheritance…
Example…
void m_display(void)
{
cout << "Name of Mother = " << m_name;
cout << "Blood Group = " << m_blood_grp;
cout << "Height = "
<< m_height_in_feet << " Feet & "
<< m_height_in_inch << " Inches ";
}
};
55
Multiple Inheritance…
Example…
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;

56
Multiple Inheritance…
Example…
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;
};

57
Multiple Inheritance…
Example…
void c_display(void)
{
f_display(); m_display();
cout << "Name of child = " << c_name;
cout << "Blood Group = " << c_blood_grp;
cout << "Height = "
<< c_height_in_feet << " Feet & "
<< c_height_in_inch << " Inches ";
}
}; 58
Multiple Inheritance…
Example…
void main()
{
child c1;
c1.f_init("Darshit","O+",5,11);
c1.m_init("Ragi","A+",5,7);
c1.c_init("Aashna",“O+",5,7);
c1.c_display();
}; Please go through
the program
“inherit5.cpp”
59
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.

Please go through
the program
“inherit6.cpp”
60
Virtual Base Classes…
Suppose, we have multilevel, multiple and
hierarchical inheritance , all together in one
derived class, there will be duplication of
members in derived class.
See the example.

61
EXAMPLE…
GRAND PARENT

PARENT 1 PARENT 2

CHILD

62
EXAMPLE…
The child class is derived from two base classes
called parent 1 and parent 2.
Parent 1 and parent 2 are derived from common
base class grand parent.
Thus child inherits the traits of grand parent via
two separate path. i.e. child will have duplicate set
of members inherited from grand parent.

63
Virtual Base Class …
This duplication can be avoided by making the
common base class as virtual base class while
declaring.

When a class is made a virtual base class, C++


ensures that only one copy of class is inherited,
regardless of how many inheritance paths exist
between the virtual base class and a derived class.

64
Declaration of Virtual Base Class…

class gp class p1: virtual public gp


{ {
… …
… };
};
class p2 : public virtual gp
{

};
65
Declaration of Virtual Base Class…

class child: public p1, public p2


{
… // Only one copy of gp will be inherited.

};

 The keywords virtual and public may be


used in either order.
66
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.

67
Constructors… Mandatory Or Not…
Base No. of Derived Class
Class Argument
Absent 0 Or >0 May Or May Not
Have Constructors
Present 0 May Or May Not
Have Constructors
Present >0 Must Have Please go
through the
Constructors program “
inherit7.cpp” &
“inherit8.cpp”

68
Order of Execution of Constructor Functions…

When both classes contains 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.

69
Order Of Execution Of
Constructor Functions…
Virtual base class constructors are always invoked
first.

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( )

70
How To Pass Arguments To Constructors? …

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.
Which in turn will pass to the base constructors in
the order in which they are declared in the derived
class.

Please go through the program “inherit8.cpp”


71
Advantage of Inheritance…
CODE REUSABILITY
In case of distributing class libraries
We might not have access to its source code.
SUPPORTS INCREMENTAL DEVELOPMENT
Allows you to add new code without causing bugs in
existing code.

72

Вам также может понравиться