SlideShare ist ein Scribd-Unternehmen logo
1 von 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…..

Weitere ähnliche Inhalte

Was ist angesagt?

Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Kamal Acharya
 
Inheritance
InheritanceInheritance
Inheritance
Tech_MX
 

Was ist angesagt? (20)

Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Constructor and Destructor in c++
Constructor  and Destructor in c++Constructor  and Destructor in c++
Constructor and Destructor in c++
 
inheritance
inheritanceinheritance
inheritance
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Binary operator overloading
Binary operator overloadingBinary operator overloading
Binary operator overloading
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Inheritance
InheritanceInheritance
Inheritance
 

Andere mochten auch

Chapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-classChapter27 polymorphism-virtual-function-abstract-class
Chapter27 polymorphism-virtual-function-abstract-class
Deepak Singh
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 

Andere mochten auch (20)

Inheritance
InheritanceInheritance
Inheritance
 
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
 
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
 
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
Inheritance in c++ ppt (Powerpoint) | inheritance in c++ ppt presentation | i...
 
Ntroduction to computer architecture and organization
Ntroduction to computer architecture and organizationNtroduction to computer architecture and organization
Ntroduction to computer architecture and organization
 

Ähnlich wie Inheritance : Extending Classes

Ähnlich wie 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
 

Mehr von Nilesh Dalvi (16)

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
 
Templates
TemplatesTemplates
Templates
 
File handling
File handlingFile handling
File handling
 
Strings
StringsStrings
Strings
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 

Kürzlich hochgeladen

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Kürzlich hochgeladen (20)

On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 

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