0% found this document useful (0 votes)
33 views95 pages

1140 1605679736 Module4

Uploaded by

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

1140 1605679736 Module4

Uploaded by

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

Inheritance

Inheritance
Inheritance: Concept of Inheritance, types of inheritance: single,
multiple, multilevel, hierarchical, hybrid inheritance
protected members
virtual base class
Overriding
Virtual base class
virtual and pure virtual functions
Implementing polymorphism.
Inheritance
The process of deriving new class from the existing
one is called inheritance

Then the old class is called base class or superclass or


parent class and the new class is called derived class or
sub class

The derived class inherits some or all properties of base


class
Inheritance allows code reusability. This implies, it
facilitates classes to reuse the existing code. The new class
Inheritance
Advantages of inheritance

Reusability of the code

to increase the reliability of the


code

to add some enhancements to


the base class
Inheritance
The derivations are three types

1. Public

2. Private

3. Protected
Protected
A member declared 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 2 classes


Inheritance
Class A
Cannot inherit Private Cannot inherit
Protected
Public

Class C : private A Class B : public A


Private Private
Protected Protected
Public Public

Class D : protected C
Private
Protected
Public
Derived class

Base class Public Private Protected

Derivation Derivation Derivation

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected


Example 1: C++ public Inheritance
Here, we have derived PublicDerived from Base in public
mode.

As a result, in PublicDerived:

•prot is inherited as protected.


•pub and getPVT() are inherited as public.
•pvt is inaccessible since it is private in Base.

Since private and protected members are not accessible


from main(), we need to create public
functions getPVT() and getProt() to access them:
Notice that the getPVT() function has been defined
inside Base.
But the getProt() function has been defined
inside PublicDerived.

This is because pvt, which is private in Base, is


inaccessible to PublicDerived.

However, prot is accessible to PublicDerived due


to public inheritance. So, getProt() can access the
protected variable from within PublicDerived.
Example 2: C++ protected Inheritance
Here, we have
derived ProtectedDerived from Base in protected
mode.

As a result, in ProtectedDerived:
•prot, pub and getPVT() are inherited as protected.
•pvt is inaccessible since it is private in Base.

As we know, protected members cannot be directly


accessed from outside the class. As a result, we
cannot use getPVT() from ProtectedDerived.

That is also why we need to create


the getPub() function in ProtectedDerived in order to
access the pub variable.
Example 3: C++ private Inheritance
Here, we have derived PrivateDerived from Base in private
mode.

As a result, in PrivateDerived:
•prot, pub and getPVT() are inherited as private.
•pvt is inaccessible since it is private in Base.

As we know, private members cannot be directly accessed


from outside the class. As a result, we cannot
use getPVT() from PrivateDerived.

That is also why we need to create the getPub() function


in PrivateDerived in order to access the pub variable.
Types of Inheritance
Types of Inheritance
Single Inheritance

B
i
n
Class A Class B : public A int main()
g
l { { {

e Public:
int c; B ob;

Public: ob.get_ab();
int a,b;
I ob.mul();
void mul()
n void get_ab()
return 0;
h {
{

e C= a*b; }
a=10;
r cout<<“Result is”<<c
i b=20;
}
t
}
a };

n };

c
i Class A Class B : public A int main()
n
{ { {
g
int a;
l int c; B ob;

e Protected:
Public: ob.get_ab();
int b;
void mul() ob.mul();
I public:
{ return 0;
n void get_ab()

h { a=10; b=20; }
int d= get_a() }

e };
c= b*d;

r cout<<“Result is”<<c
int get_a()
i }
t {

};
a return a;

n }

c
Single Inheritance
Single Inheritance
Single Inheritance
Multiple Inheritance

A B

C
Multiple Inheritance class C : public A, public
B //C is derived from class A and class
B
{
// multiple inheritance.cpp
public:
#include void sum()
using namespace std; {
class B
class A cout << "Sum = " << x +
{ y;
{
public: }
public: };
int y;
int x;
void gety() int main()
void getx()
{ {
{ C obj1; //object of
cout << "enter cout << "enter derived class C
value of x: "; value of y: "; obj1.getx();
cin >> x; cin >> y; obj1.gety();
} } obj1.sum();
return 0;
}; }; } //end of program
#include<iostream> class C: public B, public A // Note the
order
using namespace std; {
class A public:
{ C()
{ cout << "C's constructor called" <<
public: endl; }
A() };

Multiple { cout << "A's constructor called" int main()


<< endl;
Inheritan }
{
C c;
ce }; return 0;
}

class B
{
public:
B()
{ cout << "B's constructor called"
Multilevel Inheritance

C
M
U Class student { public: tot=s1+s2;
L
T protected: void get_mark(); cout<< “Total is”<<tot;
I
L int roll_num; void put_mark(); }
E }; int main()
public:
V
E void get_roll(); class result: public test {
L
I void put_roll(); { result R;
N float tot; R.get_roll();
};
H
E class test: public public: R.get_mark();
R
student void display(); R.put_roll();
I
T {
R.put_mark();
}
A
R.display();
N protected: void result: display()
C }
float s1,s2; {
Hierarchical Inheritance

B C
Hierarchical Inheritance: syntax class A // base class
{
..............
};
class B : access_specifier A // derived class
from A
{
...........
};
class C : access_specifier A // derived class
from A
{
...........
};
class D : access_specifier A // derived class
from A
{
Hierarchical Inheritance class C : public A //C is also derived from class
base
{
// hierarchial inheritance class B : public A //B is derived public:
from class base
#include <iostream> void sum()
{
using namespace std; {
public:
class A //single base class cout << "\nSum= " << x + y;
void product() }
{
{ };
public:
cout << "\nProduct= " << x * y; int main()
int x, y;
} {
void getdata()
}; B obj1; //object of derived class B
{
C obj2; //object of derived class C
cout << "\nEnter value of x
and y:\n"; obj1.getdata();
obj1.product();
cin >> x >> y;
obj2.getdata();
}
obj2.sum();
};
return 0;
} //end of program
// hierarchial Void test:: get_marks() void sports:: put_score()
inheritance.cpp
{ {
#include <iostream>
cout<<“Enter marks”; cout<<“sports score: ” <<score;
using namespace std;
cin>>sub1>>sub2; }
Class student{ class result: public test, public sports
}
Protected : int roll_no; {
Void test:: put_marks()
public: void { float total;
get_number(int);
cout<< “Marks Obtained :”<< public: void display();
void put_number(); sub1<< sub2;
}
}; }
void result:: display()
void student:: class sports
{
get_number(int r)
{
put_number();
{roll_no= r; }
Protected: float score;
put_mark();
void student:: Public:
put_number() put_score();
void get_score();
{ cout<<“Roll Number is total= sub1+ sub2+ score;
”<<roll_no; } void put_score();
cout<<“TOTAL SCORE is: ”<<total;
class test : public };
}
student void sports:: get_score()
{ {
protected: cout<<“enter sports score: ”;
int main()
{
result R;
R. get_number(10);
R. get_mark();
R. get_score();
R. display();
Return 0;
}
Hybrid Inheritance

B C

D
Virtual base class
Virtual Base Class
The child has 2 direct base classes parent1 and parent2
which themselves have a common base class grand
parent. The child inherits the traits of grand parent via
two separate paths. It can also inherit directly as shown
by the red line. The grand parent is sometimes referred to
as indirect base class.

All public and protected members of grandparent are


inherited into child twice, first via parent1 and again via
parent2. This means child would have duplicate set of
members inherited from grand parent. This introduces
ambiguity and should be avoided.
Virtual Base Class
We can prevent multiple copies of the base class being
present in a class derived from the base class through
multiple inheritance path by declaring the base class as
virtual when it is being inherited. Such a base class is
known as virtual base class

This can be done by preceding the base class name with


the keyword virtual.
Virtual base class
Virtual base class
publi
c:
Virtual base class
publi
c:
Virtual base class
publi
c:
Virtual base class
publi
c:
Virtual base class
publi
c:
Virtual base class
Virtual base class -Example
Class student with data member roll no and member functions
to get and print the number. Derive a class test from student
with data members mark1 and mark 2 and member functions
to get and print the marks. Derive another class sports from
student with data member score and get and print the sports
score. Create a class result derived from test and sports that
contains data member total to find the total of mark1,mark2
and sports score. Result class also contains member function
Polymorphism
•Polymorphism gives different meanings to the operators
or functions.
•A single function or an operator functioning in many
ways can be called polymorphism.
•Polymorphism refers to codes, operations or objects that
behave differently in different contexts.
Polymorphism
Types of Polymorphism:
1. Compile time polymorphism (Also called as static binding or early
binding)
2. Run time polymorphism. (Also called as dynamic biding or late
binding.)
Achieving Polymorphism

POLYMORPHISM

COMPILE TIME
RUN TIME

Function Overloading
Operator Overloading Virtual Function
Compile Time Polymorphism
Compile time polymorphism is implemented using overloaded
functions and operators.
The compiler will select the right function depending on the type of
parameters passed at compile time.
If function binding is done during compile time its called
compile time polymorphism.
An object is bound to its function call at compile time.
Run Time Polymorphism
At run time the appropriate version of the
function is invoked
Since the function is linked with a particular object
much later after the compilation  Late binding
It is also known as dynamic binding because the
selection of the appropriate function is done
dynamically at run time
Virtual functions are used to implement run time
polymorphism
Pointers to Objects
class A
{
int a;
public:
void show(int x)
{
a=x;
cout<<a;
}
};
void main()
{
A obj,*ptr;
ptr=&obj;
ptr->show(10);
}
Pointers to Derived Classes
A pointer of one type cannot point to an object of another
type.
However, base class pointers and derived objects are the
exceptions to this rule.
In C++, a base class pointer can also be used to point to
an object of any class derived from that base class.
For example, assume that you have a base class called A
and a class called B, which is derived from A.
Any pointer declared as a pointer to A can also be used to
point to an object of type B.
Base class pointer to derived
class A object
void main()
{
{
public:
A *ptr obj1;
void show()
B obj2;
{
ptr=&ob2;
cout<<“\n show in Base class“;}
ptr->show();
};
ptr=&ob1;
class B : public A
ptr->show();
{
}
public:
void show()
{ show in Base class
cout<<“\nshow in Derived class“; show in Base class
}
};
Overriding
If derived class defines same function as defined in its
base class, it is known as function overriding in C++.
It is used to achieve runtime polymorphism.
It enables us to provide specific implementation of the
function which is already provided by its base class
Creating a new version of an old function, in the derived
class.
Note: In function overriding, the function in parent class is
called the overridden function and function in child class is
called overriding function.
Overriding
Virtual Functions
When we use the same function name in both the base
and derived classes the base pointer even contains the
address of the derived object, always executes the
function in the base class.
To achieve run time polymorphism, the function in base
class is declared as virtual using the keyword virtual
preceding its normal declaration
When a function is made virtual the function to use at
run time is invoked based on the type of object pointed
to by the base pointer rather than the type of pointer
Virtual Functions
class A void main()
{ public: {
virtual void show() A *ptr,obj1;
{ B obj2;
cout<<" show in Base class";} ptr=&obj1
}; ptr->show();
class B : public A ptr=&obj2
{ public: ptr->show();
void show() }
{
cout<<"show in Derived class";
} show in Base class
}; show in Derived class
// CPP program to
illustrate
// concept of Virtual
Functions
#include <iostream> class derived : public base
using namespace std; int main()
{
public: {
class base { void print() base* bptr;
public: { derived d;
virtual void print() cout << "print
{ derived class" << endl; bptr = &d;
cout << "print base }
class";
// virtual function, binded at
} runtime
void show()
void show()
{ bptr->print();

{ cout << "show


derived class" << endl;
cout << "show // Non-virtual function, binded
base class" ; } at compile time
} };
bptr->show();
};
}
Concrete class
A concrete class is a class that has an implementation
for all of its methods.
They cannot have any unimplemented methods.
It can also extend an abstract class or implement an
interface as long as it implements all their methods.
It is a complete class and can be instantiated.
Abstract Class Vs Concrete class

Abstract Class Concrete Class


Abstract classes are interfaces Concrete classes are not interfaces
Abstract class is generally a base class It can be base or derived
Pure virtual function should be present in Pure virtual functions are may not present
abstract class in concrete class
Cannot create objects directly Objects can be created directly
Used to fulfil common requirement Used for specific requirement
Contains fully defined or implemented Can have both defined and undefined
methods methods

You might also like