SlideShare a Scribd company logo
1 of 68
Inheritance : Extending classesInheritance : Extending classes
By
Nilesh Dalvi
Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College.
http://www.slideshare.net/nileshdalvi01
Object oriented ProgrammingObject oriented Programming
with C++with C++
Introduction
• Inheritance is one of the most useful and
essential characteristics of oops.
• Existing classes are main components of
inheritance.
• New classes are created from existing one.
• Properties of existing classes are simply
extended to the new classes.
• New classes are called as derived classes
and existing one are base classes.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Introduction
Fig. Inheritance
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Types of Inheritance
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance
Types of Inheritance
Single inheritance:
A derived class with only one base class is
called as single inheritance.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Types of Inheritance
Multiple inheritance:
A derived class with several base classes is
called as Multiple inheritance.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Types of Inheritance
Multilevel inheritance:
The mechanism of deriving a class from
another ‘derived class’ is known as multilevel
inheritance.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Types of Inheritance
Hierarchical inheritance:
One class may be inherited by more than one
class. This process is known as hierarchical
inheritance.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Types of Inheritance
Hybrid inheritance:
It is combination of Hierarchical and Multilevel
inheritance.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Defining derived class
• A derived class can be defined by specifying its
relationship with the base class in addition to its
own details.
class derived-class-name : visibility-mode base-class-name
{
//members of derived class.
};
• The colon (:) indicates that 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
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
• Visibility-mode specifies whether the features of the base
class are privately derived or publicly derived.
• For Example:
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Defining derived class
class base
{
private:
public:
//members of base class
}
class derived : private base
{
//members of base class
}
class derived : public base
{
//members of base class
}
class derived : base
{
//members of base class
}
• public members of the base class become
private members of the derived class.
• Therefore, the public members of the base
class can only be accessed by the member
functions of the derived class.
• They are not accessible to the object of the
derived class.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Privately Inherited
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Privately Inherited
#include <iostream>
using namespace std;
//Public Derivation
class A //Base class
{
public:
int x;
};
class B : private A // Derived class
{
public:
int y;
B()
{
x = 10;
y = 20;
}
void show ()
{
cout << "X : " << x <<endl;
cout << "Y : " << y <<endl;
}
};
int main()
{
B b;
b.show ();
return 0;
}
The object b of derived class
cannot directly access the
variable x.
b.x = 10; // cannot access
class B is privately inherited.
Hence, its access is
restricted.
The object b of derived class
cannot directly access the
variable x.
b.x = 10; // cannot access
class B is privately inherited.
Hence, its access is
restricted.
• public members of the base class remains
public member in derived class.
• Therefore, they are accessible to the objects
of the derived class.
• In both cases, the private members are not
inherited and therefore, the private
members of base class will never become
the members of its derived class.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Publicly Inherited
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Publicly Inherited
#include <iostream>
using namespace std;
//Public Derivation
class A //Base class
{
public:
int x;
};
class B : public A // Derived class
{
public:
int y;
};
int main()
{
B b;
b.x = 10;
b.y = 20;
cout << "Member of A :" << b.x <<endl;
cout << "Member of B :" << b.y <<endl;
return 0;
}
In main() function, b is an
object of class B. The object
b can access the members
of class A as well as of B
through the statements:
b.x = 10;
b.y = 20;
In main() function, b is an
object of class B. The object
b can access the members
of class A as well as of B
through the statements:
b.x = 10;
b.y = 20;
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Privately Inherited
#include<iostream>
using namespace std;
class geometry
{
int length;
int breadth;
public:
void get()
{
cout << "Enter values: "<<endl;
cin >> length >> breadth;
}
int area();
};
int geometry :: area ()
{
return length * breadth;
}
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Privately Inherited
class Rect : private geometry
{
int height;
public:
void getHeight (int h)
{
get();
height = h;
}
void volume();
};
void Rect ::volume()
{
cout << "Area is: " << area ()<< endl;
cout <<"Volume is : "<< area() * height;
}
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Privately Inherited
int main()
{
Rect r;
r.getHeight (2);
//r.area();
r.volume();
return 0;
}
Output:
Enter values:
2
3
Area is: 6
Volume is: 12
• The member functions of derived class cannot
access the private member variables of base class.
• The private members of base class can be accessed
using public member functions of the same class.
• This approach makes a program lengthy.
• To overcome the problem associated with private
data, the creator of C++ introduced another access
specifier called protected.
• protected is same as private , but it allows the
derived class to access the private members
directly.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Protected data with private inheritance
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Protected data with private inheritance
class ABC
{
private: // optional
.... //visible to member functions within class
protected: //visible to member functions of its own
.... // and of its derived class
public: //visible to all functions in the program
.... //
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
#include <iostream>
using namespace std;
// PROTECTED DATA //
class A // BASE CLASS
{
protected: // protected declaration
int x;
};
class B : private A // DERIVED CLASS
{
int y;
public:
B ()
{
x = 30;
y = 40;
}
void show()
{
cout <<"n x = "<<x;
cout <<"n y = "<<y;
}
};
Protected data with private inheritance
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Protected data with private inheritance
int main()
{
B b; // DECLARATION OF OBJECT
b.show();
return 0;
}
Output :
x = 30
y = 40
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Access specifies with scopes
Sr.
No. Base class
access mode
Derived class access mode
private
derivation
public
derivation
protected
derivation
A public private public protected
B private Not inherited Not inherited Not inherited
C protected private protected protected
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Access controls of functions
Sr.
No Types of functions Access mode
private public protected
A. Class member function √ √ √
B. Derived class member x √ √
C. Friend function √ √ √
D. Friend class member √ √ √
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Single Inheritance
class ABC
{
protected:
char name [20];
int age;
};
class abc : public ABC // public derivation
{
float height;
float weight;
public:
void getdata()
{
cout << "nEnter name and age: " ;
cin >>name>>age;
cout << "nEnter height and weight: " << endl;
cin >>height>>weight;
}
void show ()
{
cout << "nName :" <<name<< "nAge :" <<age;
cout << "nHeight :" <<height << "nWeight :" <<weight;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
int main()
{
abc x;
x.getdata(); // reads data through keyboard
x.show(); // displays data on the screen
return 0;
}
Single Inheritance
class ABC has two protected
data members name and age.
class abc with two data
members inherit class ABC
publically. In main function, x
is an object of derived class
invokes member function
getdata() and show().
class ABC has two protected
data members name and age.
class abc with two data
members inherit class ABC
publically. In main function, x
is an object of derived class
invokes member function
getdata() and show().
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Multilevel Inheritance
#include<iostream>
using namespace std;
class top //base class
{
protected:
int a;
public :
void getdata()
{
cout<<"nnEnter first Number ::t";
cin>>a;
putdata();
}
void putdata()
{
cout<<"nFirst Number is ::t"<<a;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Multilevel Inheritance
//First level inheritance
class middle :public top // class middle is derived_1
{
protected:
int b;
public:
void square()
{
getdata();
b=a*a;
cout<<"nnSquare is ::t"<<b;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Multilevel Inheritance
//Second level inheritance
class bottom :public middle // class bottom is derived_2
{
int c;
public:
void cube()
{
square();
c=b*a;
cout<<"nnCube is ::t"<<c;
}
};
int main()
{
bottom b1;
b1.cube();
return 0;
}
Output :
Enter first Number :: 2
First Number is :: 2
Square is :: 4
Cube is :: 8
• When a class is derived from more than one class
then this type of inheritance is called multiple
inheritance.
• Multiple inheritance allows us to combine the
features of several existing classes as a starting
point for deriving new classes.
• Syntax:
class D : visibility-mode B, visibility-mode A
{
//members of D.
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Multiple Inheritance
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Multiple Inheritance
#include<iostream>
using namespace std;
class M
{
protected:
int m;
public:
void get_m(int);
};
class N
{
protected:
int n;
public:
void get_n(int);
};
class P: public M, public N
{
public:
void display();
};
void M :: get_m(int x)
{
m = x;
}
void N :: get_n(int y)
{
n = y;
}
void P :: display()
{
cout << "M = "<< m << endl;
cout << "N = "<< n << endl;
cout << "M*N = "<< m*n << endl;
}
int main()
{
P x;
x.get_m(10);
x.get_n(20);
x.display();
return 0;
}
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Multiple Inheritance
For example: A class Rectangle is derived
from base classes Area and Perimeter.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Multiple Inheritance
#include <iostream>
using namespace std;
class Area
{
public:
float area_calc(float l,float b)
{
return l*b;
}
};
class Perimeter
{
public:
float peri_calc(float l,float b)
{
return 2*(l+b);
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Multiple Inheritance
/* Rectangle class is derived from classes Area and Perimeter. */
class Rectangle : private Area, private Perimeter
{
private:
float length, breadth;
public:
Rectangle() : length(0.0), breadth(0.0) { }
void get_data( )
{
cout<<"Enter length: ";
cin>>length;
cout<<"Enter breadth: ";
cin>>breadth;
}
float area_calc()
{
/* Calls area_calc() of class Area and returns it. */
return Area::area_calc(length,breadth);
}
float peri_calc()
{
/* Calls peri_calc() function of class
Perimeter and returns it. */
return Perimeter::peri_calc(length,breadth);
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Multiple Inheritance
int main()
{
Rectangle r;
r.get_data();
cout<<"Area = "<<r.area_calc();
cout<<"nPerimeter = "<<r.peri_calc();
return 0;
}
Output:
Enter length: 5.1
Enter breadth: 2.3
Area = 11.73
Perimeter = 14.8
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Ambiguity Resolution in Inheritance
class M
{
public:
void display()
{
cout << "class M" << endl;
}
};
class N
{
public:
void display()
{
cout << "class N" << endl;
}
};
class P: public M, public N
{
public:
void display()
{
M :: display();
N :: display();
}
};
int main()
{
P x;
x.display();
return 0;
}
When a function
name with the same
name appears in
more than one base
class, which function
is used by the derived
class when we inherit
these two classes??
When a function
name with the same
name appears in
more than one base
class, which function
is used by the derived
class when we inherit
these two classes??
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Hierarchical Inheritance
• One class may be inherited by more than
one classes.
• Hierarchical unit shows top down style
through splitting a compound class into
several simple subclasses.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Hierarchical Inheritance
#include<iostream>
using namespace std;
class Polygon
{
protected:
int width, height;
public:
void input(int x, int y)
{
width = x;
height = y;
}
};
class Rectangle : public Polygon
{
public:
int areaR()
{
return (width * height);
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Hierarchical Inheritance
class Triangle : public Polygon
{
public:
int areaT()
{
return (width * height)/2;
}
};
int main()
{
Rectangle r;
r.input(6, 8);
cout << "Area of Rectangle ::" <<r.areaR() <<endl;
Triangle t;
t.input(6, 10);
cout << "Area of Triangle ::" <<r.areaT() <<endl;
return 0;
}
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Hybrid Inheritance
• Combination of one or more types of inheritance.
• In fig., GAME is derived from two base classes i.e.
LOCATION and PHYSIQUE.
• Class PHYSIQUE is also derived from class
PLAYER.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Hybrid Inheritance
#include<iostream>
using namespace std;
class Player
{
protected:
char name [15];
char gender;
int age;
};
class Physique : public Player
{
protected:
float height;
float weight;
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Hybrid Inheritance
class Location
{
protected:
char city [10];
char pin [10];
};
class Game : public Physique, public Player
{
protected:
char game [15];
public:
void getdata();
void show();
};
int main()
{
Game g;
g.getdata();
g.show();
return 0;
}
• When a class is derived from two or more classes, which
are derived from the same base class such type of
inheritance is known as multipath inheritance.
• Multipath inheritance consists multiple, multilevel and
hierarchical as shown in Figure.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Multipath Inheritance
• There is an ambiguity problem. When you run
program with such type inheritance. It gives a
compile time error [Ambiguity].
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Problem in Multipath Inheritance
• To overcome the ambiguity occurred due to
multipath inheritance, C++ provides the keyword
virtual.
• The keyword virtual declares the specified
classes virtual.
• When classes are declared as virtual, the
compiler takes necessary precaution to avoid
duplication of member variables.
• Thus, we make a class virtual if it is a base
class that has been used by more than one derived
class as their base class.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual base classes
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual base classes
#include<iostream>
using namespace std;
class student
{
protected:
int rno;
public:
void getnumber()
{
cout<<"Enter Roll No:";
cin>>rno;
}
void putnumber()
{
cout<<"nntRoll No:"<<rno<<"n";
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual base classes
class test:virtual public student
{
protected:
int part1,part2;
public:
void getmarks()
{
cout<<"Enter Marksn";
cout<<"Part1:";
cin>>part1;
cout<<"Part2:";
cin>>part2;
}
void putmarks()
{
cout<<"tMarks Obtainedn";
cout<<"ntPart1:"<<part1;
cout<<"ntPart2:"<<part2;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual base classes
class sports:public virtual student
{
protected:
int score;
public:
void getscore()
{
cout<<"Enter Sports Score:";
cin>>score;
}
void putscore()
{
cout<<"ntSports Score is:"<<score;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual base classes
class result:public test,public sports
{
int total;
public:
void display()
{
total=part1+part2+score;
putnumber();
putmarks();
putscore();
cout<<"ntTotal Score:"<<total;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual base classes
int main()
{
result r;
r.getnumber();
r.getmarks();
r.getscore();
r.display();
return 0;
}
Output:
Enter Roll No:111
Enter Marks
Part1:11
Part2:22
Enter Sports Score:33
Roll No:111
Marks Obtained
Part1:11
Part2:22
Sports Score is:33
Total Score:66
Problem statement:
 Define a multipath inheritance structure in which
the class master deserves information from both
account and admin classes which in turn derive
information from the class person.
 Define all four classes and write a program to
create, update, and display the information
contained in master objects.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual base classes
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual base classes
#include<iostream>
using namespace std;
class person
{
protected:
char name[20];
int code;
public:
void getcode()
{
cout<<"n Enter the code ";
cin>>code;
}
void getname()
{
cout<<"n Enter the name ";
cin>>name;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual base classes
class account:virtual public person
{
protected:
int pay;
public:
void getpay()
{
cout<<"n Enter the payment ";
cin>>pay;
}
};
class admin:virtual public person
{
protected:
int exp;
public:
void getexp()
{
cout<<"n Enter the experiance ";
cin>>exp;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual base classes
class master:public account,public admin
{
public:
void getdata()
{
getcode();
getname();
getpay();
getexp();
}
void update()
{
int c;
cout<<"n You want 2 updaten1.coden
2.namen3.paymentn4.experiance";
cout<<"nEnter ur choice ";
cin>>c;
switch(c)
{
case 1: getcode();
break;
case 2: getname();
break;
case 3: getpay();
break;
case 4: getexp();
break;
default:
cout<<"n Invalid choice";
}
}
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Virtual base classes
void putdata()
{
system("cls");
cout<<"nDetails";
cout<<"n Code "<<code<<"n Name "<<name;
cout<<"n Payment "<<pay<<"n Experiance "<<exp;
cout<<"nPress any key 2 continue ";
getchar();
}
};
int main()
{
int ch;
master m;
while(1)
{
cout<<"nMENUn1.Createn2.Updaten3.Displayn4.Exit";
cout<<"nEnter ur choice ";
cin>>ch;
switch(ch)
{
case 1: m.getdata();
break;
case 2: m.update();
break;
case 3: m.putdata();
break;
case 4: exit(0);
default:cout<<"n Invalid choice";
}
}
return 0;
}
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
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(to be inherited by other
classes).
• Constructors play an important role in initializing
objects.
• As long as no base class constructor takes any
arguments, the derived class need not have a
constructor function.
• However, 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 arguments to the base class constructor.
• In inheritance we make a objects of derived class.
Thus it make sense to pass arguments to the base
class constructor.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Constructors in Derived classes
• When both derived and base classes contain
constructors, the base class constructor is
executed first and then the constructor in the
derived class is executed.
• In multiple inheritance, the base classes are
constructed in the order in which they appear
in the declaration of the derived class.
• Similarly in multilevel inheritance, the
constructors will be executed in the order of
inheritance.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Constructors in derived class
• The general form of defining the Derived
constructor is :
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Constructors in derived class
Derived-constructor(arg1, arg2,..,argN) : base-class1(arg1),..,base-
classN(argN)
{
//body of constructor of derived class.
};
Derived-constructor(arg1, arg2,..,argN) : base-class1(arg1),..,base-
classN(argN)
{
//body of constructor of derived class.
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Constructors and Destructor in inheritance
Base-class
Constructor
Base-class
Constructor
Derived-class
constructor1
Derived-class
constructor1
Derived-class
constructorN
Derived-class
constructorN
Derived-class
DestructorN
Derived-class
DestructorN
Derived-class
Destructor1
Derived-class
Destructor1
Base-class
DestructorN
Base-class
DestructorN
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Constructors in derived class
class alpha
{
private:
int x;
public:
alpha(int i)
{
x = i;
cout << "n alpha initialized n";
}
void show_x()
{
cout << "n x = "<<x;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Constructors in derived class
class beta
{
private:
float y;
public:
beta(float j)
{
y = j;
cout << "n beta initialized n";
}
void show_y()
{
cout << "n y = "<<y;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Constructors in derived class
class gamma : public beta, public alpha
{
private:
int n,m;
public:
gamma(int a, float b, int c, int d): alpha(a), beta(b)
{
m = c;
n = d;
cout << "n gamma initialized n";
}
void show_mn()
{
cout << "n m = "<<m;
cout << "n n = "<<n;
}
};
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Constructors in derived class
int main()
{
gamma g(5, 7.65, 30, 100);
cout << "n";
g.show_x();
g.show_y();
g.show_mn();
return 0;
}
Output:
beta initialized
alpha initialized
gamma initialized
x = 5
y = 7.65
m = 30
n = 100
• The most frequent use of inheritance is for
deriving classes using existing classes, which
provides reusability. The existing classes
remains unchanged. By reusability, the
development time of software is reduced.
• The derived classes extend the properties of
base classes to generate more dominant object.
• The same base class can be used by a number of
derived classes in class hierarchy.
• When a class is derived from more than one
class, all the derived classes have the same
properties as that of base classes.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Advantages of Inheritance
• The increased time/effort it takes the program to
jump through all the levels of overloaded classes.
– If a given class has ten levels of abstraction above it, then
it will essentially take ten jumps to run through a
function defined in each of those classes
• Two classes (base and inherited class) get tightly
coupled.
– This means one cannot be used independent of each
other.
• Also with time, during maintenance adding new
features both base as well as derived classes are
required to be changed.
– If a method signature is changed then we will be affected
in both cases (inheritance & composition)
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Disadvantages of Inheritance
• If a method is deleted in the "super class" or
aggregate, then we will have to re-factor in case
of using that method.
• Here things can get a bit complicated in case of
inheritance because our programs will still
compile, but the methods of the subclass will
no longer be overriding superclass methods.
These methods will become independent
methods in their own right.
Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
Disadvantages of Inheritance
To beTo be
continued…..continued…..

More Related Content

What's hot

What's hot (20)

Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
inheritance
inheritanceinheritance
inheritance
 
04. constructor & destructor
04. constructor & destructor04. constructor & destructor
04. constructor & destructor
 
Properties and indexers in C#
Properties and indexers in C#Properties and indexers in C#
Properties and indexers in C#
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 
Classes and objects in c++
Classes and objects in c++Classes and objects in c++
Classes and objects in c++
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Class and object
Class and objectClass and object
Class and object
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 

Viewers also liked

Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cppNilesh Dalvi
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++Amresh Raj
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classDeepak Singh
 
Inheritance
InheritanceInheritance
InheritanceTech_MX
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++Nilesh Dalvi
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++Jenish Patel
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops conceptsNilesh Dalvi
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++Learn By Watch
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)Ritika Sharma
 
C++ Function
C++ FunctionC++ Function
C++ FunctionHajar
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 

Viewers also liked (20)

Inheritance
InheritanceInheritance
Inheritance
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
10 inheritance
10 inheritance10 inheritance
10 inheritance
 
Introduction to cpp
Introduction to cppIntroduction to cpp
Introduction to cpp
 
Interoduction to c++
Interoduction to c++Interoduction to c++
Interoduction to c++
 
14. Linked List
14. Linked List14. Linked List
14. Linked List
 
Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
 
Inheritance
InheritanceInheritance
Inheritance
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
Introduction to oops concepts
Introduction to oops conceptsIntroduction to oops concepts
Introduction to oops concepts
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 

Similar to Inheritance : Extending Classes

Similar to Inheritance : Extending Classes (20)

5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces5. Inheritances, Packages and Intefaces
5. Inheritances, Packages and Intefaces
 
Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
 
inheritance
inheritanceinheritance
inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
 
week14 (1).ppt
week14 (1).pptweek14 (1).ppt
week14 (1).ppt
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
 
oop database doc for studevsgdy fdsyn hdf
oop database doc for studevsgdy fdsyn hdfoop database doc for studevsgdy fdsyn hdf
oop database doc for studevsgdy fdsyn hdf
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
Inheritance Inheritance
Inheritance
 
Inheritance in c++theory
Inheritance in c++theoryInheritance in c++theory
Inheritance in c++theory
 
session 24_Inheritance.ppt
session 24_Inheritance.pptsession 24_Inheritance.ppt
session 24_Inheritance.ppt
 
OOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdfOOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdf
 

More from Nilesh Dalvi

More from Nilesh Dalvi (17)

13. Queue
13. Queue13. Queue
13. Queue
 
12. Stack
12. Stack12. Stack
12. Stack
 
11. Arrays
11. Arrays11. Arrays
11. Arrays
 
10. Introduction to Datastructure
10. Introduction to Datastructure10. Introduction to Datastructure
10. Introduction to Datastructure
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
8. String
8. String8. String
8. String
 
7. Multithreading
7. Multithreading7. Multithreading
7. Multithreading
 
6. Exception Handling
6. Exception Handling6. Exception Handling
6. Exception Handling
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
1. Overview of Java
1. Overview of Java1. Overview of Java
1. Overview of Java
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
Templates
TemplatesTemplates
Templates
 
File handling
File handlingFile handling
File handling
 
Strings
StringsStrings
Strings
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 

Recently uploaded

Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxPoojaSen20
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 

Recently uploaded (20)

Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptxCulture Uniformity or Diversity IN SOCIOLOGY.pptx
Culture Uniformity or Diversity IN SOCIOLOGY.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 

Inheritance : Extending Classes

  • 1. Inheritance : Extending classesInheritance : Extending classes By Nilesh Dalvi Lecturer, Patkar-Varde College.Lecturer, Patkar-Varde College. http://www.slideshare.net/nileshdalvi01 Object oriented ProgrammingObject oriented Programming with C++with C++
  • 2. Introduction • Inheritance is one of the most useful and essential characteristics of oops. • Existing classes are main components of inheritance. • New classes are created from existing one. • Properties of existing classes are simply extended to the new classes. • New classes are called as derived classes and existing one are base classes. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 3. Introduction Fig. Inheritance Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 4. Types of Inheritance Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). 1. Single Inheritance 2. Multiple Inheritance 3. Hierarchical Inheritance 4. Multilevel Inheritance 5. Hybrid Inheritance
  • 5. Types of Inheritance Single inheritance: A derived class with only one base class is called as single inheritance. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 6. Types of Inheritance Multiple inheritance: A derived class with several base classes is called as Multiple inheritance. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 7. Types of Inheritance Multilevel inheritance: The mechanism of deriving a class from another ‘derived class’ is known as multilevel inheritance. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 8. Types of Inheritance Hierarchical inheritance: One class may be inherited by more than one class. This process is known as hierarchical inheritance. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 9. Types of Inheritance Hybrid inheritance: It is combination of Hierarchical and Multilevel inheritance. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 10. Defining derived class • A derived class can be defined by specifying its relationship with the base class in addition to its own details. class derived-class-name : visibility-mode base-class-name { //members of derived class. }; • The colon (:) indicates that 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 Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W).
  • 11. • Visibility-mode specifies whether the features of the base class are privately derived or publicly derived. • For Example: Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Defining derived class class base { private: public: //members of base class } class derived : private base { //members of base class } class derived : public base { //members of base class } class derived : base { //members of base class }
  • 12. • public members of the base class become private members of the derived class. • Therefore, the public members of the base class can only be accessed by the member functions of the derived class. • They are not accessible to the object of the derived class. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Privately Inherited
  • 13. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Privately Inherited #include <iostream> using namespace std; //Public Derivation class A //Base class { public: int x; }; class B : private A // Derived class { public: int y; B() { x = 10; y = 20; } void show () { cout << "X : " << x <<endl; cout << "Y : " << y <<endl; } }; int main() { B b; b.show (); return 0; } The object b of derived class cannot directly access the variable x. b.x = 10; // cannot access class B is privately inherited. Hence, its access is restricted. The object b of derived class cannot directly access the variable x. b.x = 10; // cannot access class B is privately inherited. Hence, its access is restricted.
  • 14. • public members of the base class remains public member in derived class. • Therefore, they are accessible to the objects of the derived class. • In both cases, the private members are not inherited and therefore, the private members of base class will never become the members of its derived class. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Publicly Inherited
  • 15. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Publicly Inherited #include <iostream> using namespace std; //Public Derivation class A //Base class { public: int x; }; class B : public A // Derived class { public: int y; }; int main() { B b; b.x = 10; b.y = 20; cout << "Member of A :" << b.x <<endl; cout << "Member of B :" << b.y <<endl; return 0; } In main() function, b is an object of class B. The object b can access the members of class A as well as of B through the statements: b.x = 10; b.y = 20; In main() function, b is an object of class B. The object b can access the members of class A as well as of B through the statements: b.x = 10; b.y = 20;
  • 16. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Privately Inherited #include<iostream> using namespace std; class geometry { int length; int breadth; public: void get() { cout << "Enter values: "<<endl; cin >> length >> breadth; } int area(); }; int geometry :: area () { return length * breadth; }
  • 17. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Privately Inherited class Rect : private geometry { int height; public: void getHeight (int h) { get(); height = h; } void volume(); }; void Rect ::volume() { cout << "Area is: " << area ()<< endl; cout <<"Volume is : "<< area() * height; }
  • 18. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Privately Inherited int main() { Rect r; r.getHeight (2); //r.area(); r.volume(); return 0; } Output: Enter values: 2 3 Area is: 6 Volume is: 12
  • 19. • The member functions of derived class cannot access the private member variables of base class. • The private members of base class can be accessed using public member functions of the same class. • This approach makes a program lengthy. • To overcome the problem associated with private data, the creator of C++ introduced another access specifier called protected. • protected is same as private , but it allows the derived class to access the private members directly. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Protected data with private inheritance
  • 20. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Protected data with private inheritance class ABC { private: // optional .... //visible to member functions within class protected: //visible to member functions of its own .... // and of its derived class public: //visible to all functions in the program .... // };
  • 21. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). #include <iostream> using namespace std; // PROTECTED DATA // class A // BASE CLASS { protected: // protected declaration int x; }; class B : private A // DERIVED CLASS { int y; public: B () { x = 30; y = 40; } void show() { cout <<"n x = "<<x; cout <<"n y = "<<y; } }; Protected data with private inheritance
  • 22. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Protected data with private inheritance int main() { B b; // DECLARATION OF OBJECT b.show(); return 0; } Output : x = 30 y = 40
  • 23. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Access specifies with scopes Sr. No. Base class access mode Derived class access mode private derivation public derivation protected derivation A public private public protected B private Not inherited Not inherited Not inherited C protected private protected protected
  • 24. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Access controls of functions Sr. No Types of functions Access mode private public protected A. Class member function √ √ √ B. Derived class member x √ √ C. Friend function √ √ √ D. Friend class member √ √ √
  • 25. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Single Inheritance class ABC { protected: char name [20]; int age; }; class abc : public ABC // public derivation { float height; float weight; public: void getdata() { cout << "nEnter name and age: " ; cin >>name>>age; cout << "nEnter height and weight: " << endl; cin >>height>>weight; } void show () { cout << "nName :" <<name<< "nAge :" <<age; cout << "nHeight :" <<height << "nWeight :" <<weight; } };
  • 26. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). int main() { abc x; x.getdata(); // reads data through keyboard x.show(); // displays data on the screen return 0; } Single Inheritance class ABC has two protected data members name and age. class abc with two data members inherit class ABC publically. In main function, x is an object of derived class invokes member function getdata() and show(). class ABC has two protected data members name and age. class abc with two data members inherit class ABC publically. In main function, x is an object of derived class invokes member function getdata() and show().
  • 27. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Multilevel Inheritance #include<iostream> using namespace std; class top //base class { protected: int a; public : void getdata() { cout<<"nnEnter first Number ::t"; cin>>a; putdata(); } void putdata() { cout<<"nFirst Number is ::t"<<a; } };
  • 28. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Multilevel Inheritance //First level inheritance class middle :public top // class middle is derived_1 { protected: int b; public: void square() { getdata(); b=a*a; cout<<"nnSquare is ::t"<<b; } };
  • 29. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Multilevel Inheritance //Second level inheritance class bottom :public middle // class bottom is derived_2 { int c; public: void cube() { square(); c=b*a; cout<<"nnCube is ::t"<<c; } }; int main() { bottom b1; b1.cube(); return 0; } Output : Enter first Number :: 2 First Number is :: 2 Square is :: 4 Cube is :: 8
  • 30. • When a class is derived from more than one class then this type of inheritance is called multiple inheritance. • Multiple inheritance allows us to combine the features of several existing classes as a starting point for deriving new classes. • Syntax: class D : visibility-mode B, visibility-mode A { //members of D. }; Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Multiple Inheritance
  • 31. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Multiple Inheritance #include<iostream> using namespace std; class M { protected: int m; public: void get_m(int); }; class N { protected: int n; public: void get_n(int); }; class P: public M, public N { public: void display(); }; void M :: get_m(int x) { m = x; } void N :: get_n(int y) { n = y; } void P :: display() { cout << "M = "<< m << endl; cout << "N = "<< n << endl; cout << "M*N = "<< m*n << endl; } int main() { P x; x.get_m(10); x.get_n(20); x.display(); return 0; }
  • 32. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Multiple Inheritance For example: A class Rectangle is derived from base classes Area and Perimeter.
  • 33. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Multiple Inheritance #include <iostream> using namespace std; class Area { public: float area_calc(float l,float b) { return l*b; } }; class Perimeter { public: float peri_calc(float l,float b) { return 2*(l+b); } };
  • 34. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Multiple Inheritance /* Rectangle class is derived from classes Area and Perimeter. */ class Rectangle : private Area, private Perimeter { private: float length, breadth; public: Rectangle() : length(0.0), breadth(0.0) { } void get_data( ) { cout<<"Enter length: "; cin>>length; cout<<"Enter breadth: "; cin>>breadth; } float area_calc() { /* Calls area_calc() of class Area and returns it. */ return Area::area_calc(length,breadth); } float peri_calc() { /* Calls peri_calc() function of class Perimeter and returns it. */ return Perimeter::peri_calc(length,breadth); } };
  • 35. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Multiple Inheritance int main() { Rectangle r; r.get_data(); cout<<"Area = "<<r.area_calc(); cout<<"nPerimeter = "<<r.peri_calc(); return 0; } Output: Enter length: 5.1 Enter breadth: 2.3 Area = 11.73 Perimeter = 14.8
  • 36. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Ambiguity Resolution in Inheritance class M { public: void display() { cout << "class M" << endl; } }; class N { public: void display() { cout << "class N" << endl; } }; class P: public M, public N { public: void display() { M :: display(); N :: display(); } }; int main() { P x; x.display(); return 0; } When a function name with the same name appears in more than one base class, which function is used by the derived class when we inherit these two classes?? When a function name with the same name appears in more than one base class, which function is used by the derived class when we inherit these two classes??
  • 37. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Hierarchical Inheritance • One class may be inherited by more than one classes. • Hierarchical unit shows top down style through splitting a compound class into several simple subclasses.
  • 38. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Hierarchical Inheritance #include<iostream> using namespace std; class Polygon { protected: int width, height; public: void input(int x, int y) { width = x; height = y; } }; class Rectangle : public Polygon { public: int areaR() { return (width * height); } };
  • 39. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Hierarchical Inheritance class Triangle : public Polygon { public: int areaT() { return (width * height)/2; } }; int main() { Rectangle r; r.input(6, 8); cout << "Area of Rectangle ::" <<r.areaR() <<endl; Triangle t; t.input(6, 10); cout << "Area of Triangle ::" <<r.areaT() <<endl; return 0; }
  • 40. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Hybrid Inheritance • Combination of one or more types of inheritance. • In fig., GAME is derived from two base classes i.e. LOCATION and PHYSIQUE. • Class PHYSIQUE is also derived from class PLAYER.
  • 41. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Hybrid Inheritance #include<iostream> using namespace std; class Player { protected: char name [15]; char gender; int age; }; class Physique : public Player { protected: float height; float weight; };
  • 42. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Hybrid Inheritance class Location { protected: char city [10]; char pin [10]; }; class Game : public Physique, public Player { protected: char game [15]; public: void getdata(); void show(); }; int main() { Game g; g.getdata(); g.show(); return 0; }
  • 43. • When a class is derived from two or more classes, which are derived from the same base class such type of inheritance is known as multipath inheritance. • Multipath inheritance consists multiple, multilevel and hierarchical as shown in Figure. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Multipath Inheritance
  • 44. • There is an ambiguity problem. When you run program with such type inheritance. It gives a compile time error [Ambiguity]. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Problem in Multipath Inheritance
  • 45. • To overcome the ambiguity occurred due to multipath inheritance, C++ provides the keyword virtual. • The keyword virtual declares the specified classes virtual. • When classes are declared as virtual, the compiler takes necessary precaution to avoid duplication of member variables. • Thus, we make a class virtual if it is a base class that has been used by more than one derived class as their base class. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual base classes
  • 46. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual base classes #include<iostream> using namespace std; class student { protected: int rno; public: void getnumber() { cout<<"Enter Roll No:"; cin>>rno; } void putnumber() { cout<<"nntRoll No:"<<rno<<"n"; } };
  • 47. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual base classes class test:virtual public student { protected: int part1,part2; public: void getmarks() { cout<<"Enter Marksn"; cout<<"Part1:"; cin>>part1; cout<<"Part2:"; cin>>part2; } void putmarks() { cout<<"tMarks Obtainedn"; cout<<"ntPart1:"<<part1; cout<<"ntPart2:"<<part2; } };
  • 48. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual base classes class sports:public virtual student { protected: int score; public: void getscore() { cout<<"Enter Sports Score:"; cin>>score; } void putscore() { cout<<"ntSports Score is:"<<score; } };
  • 49. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual base classes class result:public test,public sports { int total; public: void display() { total=part1+part2+score; putnumber(); putmarks(); putscore(); cout<<"ntTotal Score:"<<total; } };
  • 50. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual base classes int main() { result r; r.getnumber(); r.getmarks(); r.getscore(); r.display(); return 0; } Output: Enter Roll No:111 Enter Marks Part1:11 Part2:22 Enter Sports Score:33 Roll No:111 Marks Obtained Part1:11 Part2:22 Sports Score is:33 Total Score:66
  • 51. Problem statement:  Define a multipath inheritance structure in which the class master deserves information from both account and admin classes which in turn derive information from the class person.  Define all four classes and write a program to create, update, and display the information contained in master objects. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual base classes
  • 52. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual base classes #include<iostream> using namespace std; class person { protected: char name[20]; int code; public: void getcode() { cout<<"n Enter the code "; cin>>code; } void getname() { cout<<"n Enter the name "; cin>>name; } };
  • 53. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual base classes class account:virtual public person { protected: int pay; public: void getpay() { cout<<"n Enter the payment "; cin>>pay; } }; class admin:virtual public person { protected: int exp; public: void getexp() { cout<<"n Enter the experiance "; cin>>exp; } };
  • 54. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual base classes class master:public account,public admin { public: void getdata() { getcode(); getname(); getpay(); getexp(); } void update() { int c; cout<<"n You want 2 updaten1.coden 2.namen3.paymentn4.experiance"; cout<<"nEnter ur choice "; cin>>c; switch(c) { case 1: getcode(); break; case 2: getname(); break; case 3: getpay(); break; case 4: getexp(); break; default: cout<<"n Invalid choice"; } }
  • 55. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Virtual base classes void putdata() { system("cls"); cout<<"nDetails"; cout<<"n Code "<<code<<"n Name "<<name; cout<<"n Payment "<<pay<<"n Experiance "<<exp; cout<<"nPress any key 2 continue "; getchar(); } }; int main() { int ch; master m; while(1) { cout<<"nMENUn1.Createn2.Updaten3.Displayn4.Exit"; cout<<"nEnter ur choice "; cin>>ch; switch(ch) { case 1: m.getdata(); break; case 2: m.update(); break; case 3: m.putdata(); break; case 4: exit(0); default:cout<<"n Invalid choice"; } } return 0; }
  • 56. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). 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(to be inherited by other classes).
  • 57. • Constructors play an important role in initializing objects. • As long as no base class constructor takes any arguments, the derived class need not have a constructor function. • However, 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 arguments to the base class constructor. • In inheritance we make a objects of derived class. Thus it make sense to pass arguments to the base class constructor. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Constructors in Derived classes
  • 58. • When both derived and base classes contain constructors, the base class constructor is executed first and then the constructor in the derived class is executed. • In multiple inheritance, the base classes are constructed in the order in which they appear in the declaration of the derived class. • Similarly in multilevel inheritance, the constructors will be executed in the order of inheritance. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Constructors in derived class
  • 59. • The general form of defining the Derived constructor is : Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Constructors in derived class Derived-constructor(arg1, arg2,..,argN) : base-class1(arg1),..,base- classN(argN) { //body of constructor of derived class. }; Derived-constructor(arg1, arg2,..,argN) : base-class1(arg1),..,base- classN(argN) { //body of constructor of derived class. };
  • 60. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Constructors and Destructor in inheritance Base-class Constructor Base-class Constructor Derived-class constructor1 Derived-class constructor1 Derived-class constructorN Derived-class constructorN Derived-class DestructorN Derived-class DestructorN Derived-class Destructor1 Derived-class Destructor1 Base-class DestructorN Base-class DestructorN
  • 61. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Constructors in derived class class alpha { private: int x; public: alpha(int i) { x = i; cout << "n alpha initialized n"; } void show_x() { cout << "n x = "<<x; } };
  • 62. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Constructors in derived class class beta { private: float y; public: beta(float j) { y = j; cout << "n beta initialized n"; } void show_y() { cout << "n y = "<<y; } };
  • 63. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Constructors in derived class class gamma : public beta, public alpha { private: int n,m; public: gamma(int a, float b, int c, int d): alpha(a), beta(b) { m = c; n = d; cout << "n gamma initialized n"; } void show_mn() { cout << "n m = "<<m; cout << "n n = "<<n; } };
  • 64. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Constructors in derived class int main() { gamma g(5, 7.65, 30, 100); cout << "n"; g.show_x(); g.show_y(); g.show_mn(); return 0; } Output: beta initialized alpha initialized gamma initialized x = 5 y = 7.65 m = 30 n = 100
  • 65. • The most frequent use of inheritance is for deriving classes using existing classes, which provides reusability. The existing classes remains unchanged. By reusability, the development time of software is reduced. • The derived classes extend the properties of base classes to generate more dominant object. • The same base class can be used by a number of derived classes in class hierarchy. • When a class is derived from more than one class, all the derived classes have the same properties as that of base classes. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Advantages of Inheritance
  • 66. • The increased time/effort it takes the program to jump through all the levels of overloaded classes. – If a given class has ten levels of abstraction above it, then it will essentially take ten jumps to run through a function defined in each of those classes • Two classes (base and inherited class) get tightly coupled. – This means one cannot be used independent of each other. • Also with time, during maintenance adding new features both base as well as derived classes are required to be changed. – If a method signature is changed then we will be affected in both cases (inheritance & composition) Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Disadvantages of Inheritance
  • 67. • If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of using that method. • Here things can get a bit complicated in case of inheritance because our programs will still compile, but the methods of the subclass will no longer be overriding superclass methods. These methods will become independent methods in their own right. Nilesh Dalvi, Lecturer@Patkar-Varde College, Goregaon(W). Disadvantages of Inheritance