SlideShare a Scribd company logo
OBJECT-ORIENTED PROGRAMMING
(OOP)
Week – 03
Lecturer:Sobia Iftikhar
Object Relationship
◦ Object oriented programming generally support 4 types of relationships that
are:
• Is-a relationship
Inheritance
• Part-of relationship
Composition
• has-a relationship
Aggregation and Association
Inheritance : Is-a Relationship
◦ Sometimes, one class is an extension of another class.
◦ inheritance is an is-a relationship. We use inheritance only if an is-a relationship is present between the
two classes.
◦ It is just like saying that “A is type of B”.
◦ For example
◦ is “Apple is a fruit”, “Ferrari is a car”.
◦ A car is a vehicle.
◦ Orange is a fruit.
◦ A surgeon is a doctor.
◦ A dog is an animal.
Inheritance
◦ The technique of deriving a new class from an old one is called inheritance
◦ Capability of a class to derive properties and characteristics from another class.
◦ The extended (or child) class contains all the features of its base (or parent) class, and may
additionally have some unique features of its own.
Inheritance cont.
◦ Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.
Super Class: The class whose properties are inherited by sub class is called Base Class
or Super class.
For example,
Inheritance - Real World Scenario
◦ HOD is a staff member of college.
◦ All teachers are staff member of college.
Example
#include <bits/stdc++.h>
using namespace std;
//Base class
class Parent
{ public:
int id_p;
};
// Sub class inheriting from Base Class(Parent)
class Child : public Parent
{
public:
int id_c; };
//main function
int main()
{
Child obj1;
// An object of class child has all data members
// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;
return 0;
}
Example
// C++ program to demonstrate
inheritance
#include <iostream>
using namespace std;
// base class
class Animal {
public:
void eat()
{ cout << "I can eat!" << endl; }
void sleep()
{ cout << "I can sleep!" << endl;
} };
// derived class
class Dog : public Animal {
public:
void bark()
{ cout << "I can bark! Woof
woof!!" << endl; }
};
int main() {
// Create object of the Dog class Dog
dog1;
// Calling members of the base class
dog1.eat();
dog1.sleep();
// Calling member of the derived class
dog1.bark();
return 0;
}
I can eat!
I can sleep!
I can bark! Woof woof!!
Output
Why and when to use inheritance?
◦ Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes.
Why and when to use inheritance?
◦ You can clearly see that above process results in duplication of same code 3
times. This increases the chances of error and data redundancy. To avoid this
type of situation, inheritance is used.
◦ If we create a class Vehicle and write these three functions in it and inherit the
rest of the classes from the vehicle class, then we can simply avoid the
duplication of data and increase re-usability.
Why and when to use inheritance?
Implementing inheritance in C++
◦ Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Modes of Inheritance
◦ Public mode: If we derive a sub class from a public base class. Then the
public member of the base class will become public in the derived class and
protected members of the base class will become protected in derived class.
◦ Protected mode: If we derive a sub class from a Protected base class.
Then both public member and protected members of the base class will
become protected in derived class.
◦ Private mode: If we derive a sub class from a Private base class. Then
both public member and protected members of the base class will become
Private in derived class.
Mode of Inheritance
class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public
// y is protected
// z is not
accessible from B
};
class C : protected
A
{
// x is protected
// y is protected
// z is not
accessible from C
};
class D : private
A // 'private' is
default for classes
{
// x is private
// y is private
// z is not
accessible from D
};
Mode of Inheritance
Types of Inheritance in C++
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid (Virtual) Inheritance
Single Inheritance
◦ In single inheritance, a class is allowed to inherit from only one
class. i.e. one sub class is inherited by one base class only.
Single Inheritance (Continue..)
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
// sub class derived from two base classes
class Car: public Vehicle{
};
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
Multiple Inheritance
◦ Multiple Inheritance is a feature of C++ where a class can inherit from more
than one classes. i.e one sub class is inherited from more than one base
classes.
Multiple Inheritance (Continue..)
◦ Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2, ....{//body of subclass};
class output : public stud, public extracurriculam
{ int tot, avg;
public:
void display() {
tot = (m1 + m2 + xm);
avg = tot / 3;
cout << "nntRoll No : " << roll <<
"ntTotal : " << tot;
cout << "ntAverage : " << avg; } };
int main() {
output O;
O.get();
O.getsm();
O.display(); }
class stud {
protected:
int roll, m1, m2;
public:
void get()
{ cout << "Enter the Roll No.: ";
cin >> roll;
cout << "Enter the two highest marks: ";
cin >> m1 >> m2; } };
class extracurriculam {
protected:
int xm;
public:
void getsm()
{ cout << "nEnter the mark for Extra
Curriculam Activities: "; cin >> xm; } }
Multilevel Inheritance
◦ In this type of inheritance, a derived class is created from another
derived class.
Multilevel Inheritance (Continue..)
class derived2 : public derived
{ void display3()
{ cout << "n2nd Derived class content."; }
};
int main()
{ derived2 D;
//D.display3();
D.display2();
D.display1(); }
#include <iostream>
using namespace std;
class base {
public:
void display1()
{ cout << "nBase class content."; } };
class derived : public base {
public:
void display2()
{ cout << "1st derived class content."; }
};
Hierarchical Inheritance
In this type of inheritance, more than one sub class is inherited from a single base class. i.e.
more than one derived class is created from a single base class.
Hierarchical Inheritance (Continue..)
include <iostream>
#include <string.h>
using namespace std;
class member {
char gender[10];
int age;
public:
void get()
{
cout << "Age: "; cin >> age;
cout << "Gender: "; cin >> gender;
}
void disp()
{
cout << "Age: " << age << endl;
cout << "Gender: " << gender << endl;
}};
class stud : public member {
char level[20];
public:
void getdata()
{
member::get();
cout << "Class: "; cin >> level;
}
void disp2()
{
member::disp();
cout << "Level: " << level << endl;
}
};
class staff : public member {
float salary;
public:
void getdata()
{
member::get();
cout << "Salary: Rs."; cin >> salary;
}
void disp3()
{
member::disp();
cout << "Salary: Rs." << salary <<
endl;
Student
Enter data
Age: 12
Gender: Female
Class: 10
Displaying data
Age: 12
Gender: Female
Output
int main()
{
member M;
staff S;
stud s;
cout << "Student" << endl;
cout << "Enter data" << endl;
s.getdata();
cout << endl
<< "Displaying data" << endl;
s.disp();
cout << endl
<< "Staff Data" << endl;
cout << "Enter data" << endl;
S.getdata();
cout << endl
<< "Displaying data" << endl;
S.disp();
}
Staff Data
Enter data
Age: 12
Gender: male
Salary: Rs.100000
Displaying data
Age: 12
Gender: male
Hybrid (Virtual) Inheritance
◦ Hybrid Inheritance is implemented by combining more than one type of inheritance. For
example: Combining Hierarchical inheritance and Multiple Inheritance.
Hybrid Inheritance (Continue..)
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
//base class
class Fare
{
public:
Fare()
{
cout<<"Fare of Vehiclen";
} };
// first sub class
class Car: public Vehicle
{
};
// second sub class
class Bus: public Vehicle, public
Fare
{
};
This is a Vehicle
Fare of Vehicle
Output
// main function
int main()
{
// creating object of sub class will
// invoke the constructor of base
class
Bus obj2;
return 0;
}
Order of constructor and Destructor
call
◦ Whenever we create an object of a class, the default constructor of that class is invoked automatically to
initialize the members of the class.
If we inherit a class from another class and create an object of the derived class, it is clear that the default
constructor of the derived class will be invoked but before that the default constructor of all of the base
classes will be invoke, i.e the order of invokation is that the base class’s default constructor will be
invoked first and then the derived class’s default constructor will be invoked.
Order of constructor and Destructor
call
Example
#include <iostream>
using namespace std;
// base class
class Parent
{
public:
// base class constructor
Parent()
{
cout << "Inside base class" << endl;
}
};
// sub class
class Child : public Parent
{
public:
//sub class constructor
Child()
{
cout << "Inside sub class" << endl;
}
};
Inside base class
Inside sub class
Output
// main function
int main() {
// creating object of sub class
Child obj;
return 0;
}
Concept: Base class Default Constructor in
Derived class Constructors!
class Base
{
int x;
public:
// default constructor
Base()
{
cout << "Base default
constructorn";
}
};
class Derived : public Base
{
int y;
public:
// default constructor
Derived()
{
cout << "Derived default
constructorn";
}
// parameterized constructor
Derived(int i)
{
cout << "Derived parameterized
constructorn";
}
Base default constructor
Base default constructor
Derived default constructor
Base default constructor
Derived parameterized constructor
Output
int main()
{
Base b;
Derived d1;
Derived d2(10);
}
Example
Concept: Calling parameterized constructor
of base class in derived class constructor!
◦ To call the parameterized constructor of base class when derived class’s
parameterized constructor is called, you have to explicitly specify the base
class’s parameterized constructor in derived class
Concept: Calling parameterized constructor
of base class in derived class constructor!
class Base
{
int x;
public:
// parameterized
constructor
Base(int i)
{
x = i;
cout << "Base
Parameterized
Constructorn";
}
};
class Derived : public Base
{
int y;
public:
// parameterized
constructor
Derived(int j):Base(j)
{
y = j;
cout << "Derived
Parameterized
Constructorn";
}
};
Base Parameterized Constructor
Derived Parameterized Constructor
Output
int main()
{
Derived d(10) ;
}
Example
Important Points
◦ Whenever the derived class’s default constructor is called, the base class’s default
constructor is called automatically.
◦ To call the parameterized constructor of base class inside the parameterized
constructor of sub class, we have to mention it explicitly.
Exercise
◦ Create two classes named Mammals and MarineAnimals. Create another class named
BlueWhale which inherits both the above classes. Now, create a function in each of these
classes which prints "I am mammal", "I am a marine animal" and "I belong to both the
categories: Mammals as well as Marine Animals" respectively. Now, create an object for
each of the above class and try calling
1 - function of Mammals by the object of Mammal
2 - function of MarineAnimal by the object of MarineAnimal
3 - function of BlueWhale by the object of BlueWhale
4 - function of each of its parent by the object of BlueWhale
◦ Types of Inheritance = ??
◦ Write a Basic Sekeletone
Exercise
◦ Create a base class named Person with name, age, and gender as its data members. Define a constructor
to initialize the data members and a function display() to display the details of the person.
◦ Create a derived class named Employee which inherits Person class. Define empid and salary as its data
members. Define a constructor to initialize the data members and override the display() function to
display the details of the employee.
◦ Create another derived class named Manager which inherits Employee class. Define department as its
data member. Define a constructor to initialize the data members and override the display() function to
display the details of the manager.
◦ Create an object for Person, Employee, and Manager classes and call their display() functions.
Types of Inheritance = ??
Write a Basic Sekeletone
Data Code Hiding
Polymorphism
◦ Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means
many and morphs means forms. So polymorphism means many forms.
◦ Polymorphism is a feature of OOPs that allows the object to behave differently in different
conditions.
◦ we can define polymorphism as the ability of a message to be displayed in more than one form.
◦ First concept given by Hindley and Milner.
◦ The basic idea behind the polymorphism is that compiler does not which function to call at
compile time.
Polymorphism-contd.
◦ A real-life example of polymorphism, a person at the same time can have different characteristics. Like a
man at the same time is a father, a husband, an employee.
◦ So the same person posses different behavior in different situations. This is called polymorphism.
Polymorphism-contd.
Real life example of Polymorphism
Suppose if you are in class room that time you behave like a student, when you are in
market at that time you behave like a customer, when you at your home at that time you
behave like a son or daughter, Here one person have different-different behaviors.
Polymorphism Importance
◦ Polymorphism saves the programmer a lot of time in re-creating code.
◦ You don't want to have to write completely different modules for every possible permutation.
◦ For example, if you had methods for tree growth, it would be hard to have to write a specific growth
method for maple, spruce, pine, etc. Instead, you can have a growth function that spans across all tree
types.
Difference between
Inheritance & Polymorphism
S.NO INHERITANCE POLYMORPHISM
1.
Inheritance is one in which a new class is created
(derived class) that inherits the features from the
already existing class(Base class).
Whereas polymorphism is that which can be defined in
multiple forms.
2. It is basically applied to classes. Whereas it is basically applied to functions or methods.
3.
Inheritance supports the concept of reusability and
reduces code length in object-oriented programming.
Polymorphism allows the object to decide which form
of the function to implement at compile-time
(overloading) as well as run-time (overriding).
4.
Inheritance can be single, hybrid, multiple,
hierarchical and multilevel inheritance.
Whereas it can be compiled-time polymorphism
(overload) as well as run-time polymorphism
(overriding).
Type of Polymorphism
◦Static / Compile time polymorphism
◦Dynamic / Run time polymorphism
Static / Compile time polymorphism
◦ It is also called Early Binding
◦ It happens where more than one methods share the same name with different parameters or
signature and different return type.
◦ It is known as Early Binding because the compiler is aware of the functions with same name
and also which overloaded function is to be called is known at compile time.
Static / Compile time polymorphism
using namespace std;
class Geeks
{
public:
// function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}
// function with same name but 1 double parameter
void func(double x)
{
cout << "value of x is " << x << endl;
}
// function with same name and 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};
int main() {
Geeks obj1;
// Which function is called will depend on the
parameters passed
// The first 'func' is called
obj1.func(7);
// The second 'func' is called
obj1.func(9.132);
// The third 'func' is called
obj1.func(85,64);
return 0;
}
Dynamic / Run time polymorphism
◦ This refers to the entity which changes its form depending on circumstances at runtime.
◦ Method Overriding uses runtime Polymorphism.
◦ Runtime Polymorphism is done using virtual and inheritance.
◦ It is also called Late Binding.
Dynamic / Run time polymorphism
include <bits/stdc++.h>
using namespace std;
class base
{
public:
void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
class derived:public base
{
public:
void print () //print () is already virtual function in derived class, we
could also declared as virtual void print () explicitly
{ cout<< "print derived class" <<endl; }
void show ()
{ cout<< "show derived class" <<endl; }
};
//main function
int main()
{
base *bptr;
derived d;
bptr = &d;
//virtual function, binded at runtime (Runtime
polymorphism)
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
return 0;
}
Virtual Function
◦ If it is necessary to use a single pointer to refer to all the different classes’ objects. This is
because we will have to create a pointer to the base class that refers to all the derived
objects.
◦ But, when the base class pointer contains the derived class address, the object always
executes the base class function. For resolving this problem, we use the virtual function.
Introduction to inheritance and different types of inheritance
The vtable for the base class is straightforward. In the
case of the derived class, only function1_virtual is
overridden.
Hence we see that in the derived class vtable, function
pointer for function1_virtual points to the overridden
function in the derived class. On the other hand function
pointer for function2_virtual points to a function in the
base class.
Thus in the above program when the base pointer is
assigned a derived class object, the base pointer points to
_vptr of the derived class.
So when the call b->function1_virtual() is made, the
function1_virtual from the derived class is called and
when the function call b->function2_virtual() is made, as
this function pointer points to the base class function, the
base class function is called.
Case-Study
◦ Define a class batsman with the following specifications:
Private members:
bcode 4 digits code number
bname 20 characters
innings, notout, runs integer type
batavg it is calculated according to the formula –
batavg =runs/(innings-notout)
calcavg() Function to compute batavg
Public members:
readdata() Function to accept value from bcode, name, innings, notout
and invoke the function calcavg()
displaydata() Function to display the data members on the screen.

More Related Content

PPTX
polymorphism
Imtiaz Hussain
 
PPTX
Polymorphism
Kumar Gaurav
 
PPTX
Access modifiers in java
Madishetty Prathibha
 
PPTX
This keyword in java
Hitesh Kumar
 
PPTX
Packages in java
SahithiReddyEtikala
 
PPT
Unit 7 Java
arnold 7490
 
PPTX
Dynamic method dispatch
yugandhar vadlamudi
 
PPTX
Pure virtual function and abstract class
Amit Trivedi
 
polymorphism
Imtiaz Hussain
 
Polymorphism
Kumar Gaurav
 
Access modifiers in java
Madishetty Prathibha
 
This keyword in java
Hitesh Kumar
 
Packages in java
SahithiReddyEtikala
 
Unit 7 Java
arnold 7490
 
Dynamic method dispatch
yugandhar vadlamudi
 
Pure virtual function and abstract class
Amit Trivedi
 

What's hot (20)

PPT
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
PPTX
[OOP - Lec 07] Access Specifiers
Muhammad Hammad Waseem
 
PPT
Applet life cycle
myrajendra
 
PDF
Java IO
UTSAB NEUPANE
 
PPTX
Java constructors
QUONTRASOLUTIONS
 
PPTX
Java OOP Concept
NikitaGour5
 
PDF
History of C#
aschlapsi
 
PDF
Polymorphism In Java
Spotle.ai
 
PDF
Example for Virtual and Pure Virtual function.pdf
rajaratna4
 
PPTX
Super keyword in java
Hitesh Kumar
 
PPTX
Friend functions
Megha Singh
 
PDF
CLASS & OBJECT IN JAVA
Riaj Uddin Mahi
 
PPTX
Exceptions in Java
Vadym Lotar
 
PPTX
Object Oriented Programming in Java _lecture 1
Mahmoud Alfarra
 
PDF
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
PPTX
java interface and packages
VINOTH R
 
PPTX
encapsulation
shalini392
 
PPTX
[OOP - Lec 18] Static Data Member
Muhammad Hammad Waseem
 
PPTX
Concept of OOPS with real life examples
Neha Sharma
 
PPTX
Java class,object,method introduction
Sohanur63
 
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
[OOP - Lec 07] Access Specifiers
Muhammad Hammad Waseem
 
Applet life cycle
myrajendra
 
Java IO
UTSAB NEUPANE
 
Java constructors
QUONTRASOLUTIONS
 
Java OOP Concept
NikitaGour5
 
History of C#
aschlapsi
 
Polymorphism In Java
Spotle.ai
 
Example for Virtual and Pure Virtual function.pdf
rajaratna4
 
Super keyword in java
Hitesh Kumar
 
Friend functions
Megha Singh
 
CLASS & OBJECT IN JAVA
Riaj Uddin Mahi
 
Exceptions in Java
Vadym Lotar
 
Object Oriented Programming in Java _lecture 1
Mahmoud Alfarra
 
Memory Management C++ (Peeling operator new() and delete())
Sameer Rathoud
 
java interface and packages
VINOTH R
 
encapsulation
shalini392
 
[OOP - Lec 18] Static Data Member
Muhammad Hammad Waseem
 
Concept of OOPS with real life examples
Neha Sharma
 
Java class,object,method introduction
Sohanur63
 
Ad

Similar to Introduction to inheritance and different types of inheritance (20)

PPT
Inheritance.ppt
JP2B1197685ARamSaiPM
 
PPTX
Week 8 - OOP Inheritance11111111111.pptx
NajamUlHassan73
 
PPTX
Inheritance.pptx
RutujaTandalwade
 
PDF
Chapter 6 and inheritance OOP C++ tu ioe
EZERR1
 
PPTX
Object Oriented Design and Programming Unit-03
Sivakumar M
 
PPTX
Inheritance in c++
Vishal Patil
 
DOCX
oop database doc for studevsgdy fdsyn hdf
itxminahil29
 
PPTX
00ps inheritace using c++
sushamaGavarskar1
 
PDF
lecture-2021inheritance-160705095417.pdf
AneesAbbasi14
 
PPTX
[OOP - Lec 20,21] Inheritance
Muhammad Hammad Waseem
 
PDF
chapter-10-inheritance.pdf
study material
 
PPT
Inheritance
poonam.rwalia
 
PPTX
INHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM.pptx
DeepasCSE
 
PPTX
Inheritance in c++ by Manan Pasricha
MananPasricha
 
PPT
session 24_Inheritance.ppt
NAVANEETCHATURVEDI2
 
PDF
OOP Assign No.03(AP).pdf
Anant240318
 
PPTX
INHERITANCE.pptx
AteeqaKokab1
 
PDF
Inheritance
Pranali Chaudhari
 
PPT
02-OOP with Java.ppt
EmanAsem4
 
PPT
025466482929 -OOP with Java Development Kit.ppt
DakshinaPahan
 
Inheritance.ppt
JP2B1197685ARamSaiPM
 
Week 8 - OOP Inheritance11111111111.pptx
NajamUlHassan73
 
Inheritance.pptx
RutujaTandalwade
 
Chapter 6 and inheritance OOP C++ tu ioe
EZERR1
 
Object Oriented Design and Programming Unit-03
Sivakumar M
 
Inheritance in c++
Vishal Patil
 
oop database doc for studevsgdy fdsyn hdf
itxminahil29
 
00ps inheritace using c++
sushamaGavarskar1
 
lecture-2021inheritance-160705095417.pdf
AneesAbbasi14
 
[OOP - Lec 20,21] Inheritance
Muhammad Hammad Waseem
 
chapter-10-inheritance.pdf
study material
 
Inheritance
poonam.rwalia
 
INHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM.pptx
DeepasCSE
 
Inheritance in c++ by Manan Pasricha
MananPasricha
 
session 24_Inheritance.ppt
NAVANEETCHATURVEDI2
 
OOP Assign No.03(AP).pdf
Anant240318
 
INHERITANCE.pptx
AteeqaKokab1
 
Inheritance
Pranali Chaudhari
 
02-OOP with Java.ppt
EmanAsem4
 
025466482929 -OOP with Java Development Kit.ppt
DakshinaPahan
 
Ad

Recently uploaded (20)

PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
Autodock-for-Beginners by Rahul D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
CDH. pptx
AneetaSharma15
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
PDF
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
Autodock-for-Beginners by Rahul D Jawarkar.pptx
Rahul Jawarkar
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
CDH. pptx
AneetaSharma15
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 

Introduction to inheritance and different types of inheritance

  • 1. OBJECT-ORIENTED PROGRAMMING (OOP) Week – 03 Lecturer:Sobia Iftikhar
  • 2. Object Relationship ◦ Object oriented programming generally support 4 types of relationships that are: • Is-a relationship Inheritance • Part-of relationship Composition • has-a relationship Aggregation and Association
  • 3. Inheritance : Is-a Relationship ◦ Sometimes, one class is an extension of another class. ◦ inheritance is an is-a relationship. We use inheritance only if an is-a relationship is present between the two classes. ◦ It is just like saying that “A is type of B”. ◦ For example ◦ is “Apple is a fruit”, “Ferrari is a car”. ◦ A car is a vehicle. ◦ Orange is a fruit. ◦ A surgeon is a doctor. ◦ A dog is an animal.
  • 4. Inheritance ◦ The technique of deriving a new class from an old one is called inheritance ◦ Capability of a class to derive properties and characteristics from another class. ◦ The extended (or child) class contains all the features of its base (or parent) class, and may additionally have some unique features of its own.
  • 5. Inheritance cont. ◦ Sub Class: The class that inherits properties from another class is called Sub class or Derived Class. Super Class: The class whose properties are inherited by sub class is called Base Class or Super class. For example,
  • 6. Inheritance - Real World Scenario ◦ HOD is a staff member of college. ◦ All teachers are staff member of college.
  • 7. Example #include <bits/stdc++.h> using namespace std; //Base class class Parent { public: int id_p; }; // Sub class inheriting from Base Class(Parent) class Child : public Parent { public: int id_c; }; //main function int main() { Child obj1; // An object of class child has all data members // and member functions of class parent obj1.id_c = 7; obj1.id_p = 91; cout << "Child id is " << obj1.id_c << endl; cout << "Parent id is " << obj1.id_p << endl; return 0; }
  • 8. Example // C++ program to demonstrate inheritance #include <iostream> using namespace std; // base class class Animal { public: void eat() { cout << "I can eat!" << endl; } void sleep() { cout << "I can sleep!" << endl; } }; // derived class class Dog : public Animal { public: void bark() { cout << "I can bark! Woof woof!!" << endl; } }; int main() { // Create object of the Dog class Dog dog1; // Calling members of the base class dog1.eat(); dog1.sleep(); // Calling member of the derived class dog1.bark(); return 0; } I can eat! I can sleep! I can bark! Woof woof!! Output
  • 9. Why and when to use inheritance? ◦ Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes.
  • 10. Why and when to use inheritance? ◦ You can clearly see that above process results in duplication of same code 3 times. This increases the chances of error and data redundancy. To avoid this type of situation, inheritance is used. ◦ If we create a class Vehicle and write these three functions in it and inherit the rest of the classes from the vehicle class, then we can simply avoid the duplication of data and increase re-usability.
  • 11. Why and when to use inheritance?
  • 12. Implementing inheritance in C++ ◦ Syntax: class subclass_name : access_mode base_class_name { //body of subclass };
  • 13. Modes of Inheritance ◦ Public mode: If we derive a sub class from a public base class. Then the public member of the base class will become public in the derived class and protected members of the base class will become protected in derived class. ◦ Protected mode: If we derive a sub class from a Protected base class. Then both public member and protected members of the base class will become protected in derived class. ◦ Private mode: If we derive a sub class from a Private base class. Then both public member and protected members of the base class will become Private in derived class.
  • 14. Mode of Inheritance class A { public: int x; protected: int y; private: int z; }; class B : public A { // x is public // y is protected // z is not accessible from B }; class C : protected A { // x is protected // y is protected // z is not accessible from C }; class D : private A // 'private' is default for classes { // x is private // y is private // z is not accessible from D };
  • 16. Types of Inheritance in C++ 1. Single Inheritance 2. Multiple Inheritance 3. Multilevel Inheritance 4. Hierarchical Inheritance 5. Hybrid (Virtual) Inheritance
  • 17. Single Inheritance ◦ In single inheritance, a class is allowed to inherit from only one class. i.e. one sub class is inherited by one base class only.
  • 18. Single Inheritance (Continue..) Syntax: class subclass_name : access_mode base_class { //body of subclass }; // sub class derived from two base classes class Car: public Vehicle{ }; // main function int main() { // creating object of sub class will // invoke the constructor of base classes Car obj; return 0; } #include <iostream> using namespace std; // base class class Vehicle { public: Vehicle() { cout << "This is a Vehicle" << endl; } };
  • 19. Multiple Inheritance ◦ Multiple Inheritance is a feature of C++ where a class can inherit from more than one classes. i.e one sub class is inherited from more than one base classes.
  • 20. Multiple Inheritance (Continue..) ◦ Syntax: class subclass_name : access_mode base_class1, access_mode base_class2, ....{//body of subclass}; class output : public stud, public extracurriculam { int tot, avg; public: void display() { tot = (m1 + m2 + xm); avg = tot / 3; cout << "nntRoll No : " << roll << "ntTotal : " << tot; cout << "ntAverage : " << avg; } }; int main() { output O; O.get(); O.getsm(); O.display(); } class stud { protected: int roll, m1, m2; public: void get() { cout << "Enter the Roll No.: "; cin >> roll; cout << "Enter the two highest marks: "; cin >> m1 >> m2; } }; class extracurriculam { protected: int xm; public: void getsm() { cout << "nEnter the mark for Extra Curriculam Activities: "; cin >> xm; } }
  • 21. Multilevel Inheritance ◦ In this type of inheritance, a derived class is created from another derived class.
  • 22. Multilevel Inheritance (Continue..) class derived2 : public derived { void display3() { cout << "n2nd Derived class content."; } }; int main() { derived2 D; //D.display3(); D.display2(); D.display1(); } #include <iostream> using namespace std; class base { public: void display1() { cout << "nBase class content."; } }; class derived : public base { public: void display2() { cout << "1st derived class content."; } };
  • 23. Hierarchical Inheritance In this type of inheritance, more than one sub class is inherited from a single base class. i.e. more than one derived class is created from a single base class.
  • 24. Hierarchical Inheritance (Continue..) include <iostream> #include <string.h> using namespace std; class member { char gender[10]; int age; public: void get() { cout << "Age: "; cin >> age; cout << "Gender: "; cin >> gender; } void disp() { cout << "Age: " << age << endl; cout << "Gender: " << gender << endl; }}; class stud : public member { char level[20]; public: void getdata() { member::get(); cout << "Class: "; cin >> level; } void disp2() { member::disp(); cout << "Level: " << level << endl; } }; class staff : public member { float salary; public: void getdata() { member::get(); cout << "Salary: Rs."; cin >> salary; } void disp3() { member::disp(); cout << "Salary: Rs." << salary << endl; Student Enter data Age: 12 Gender: Female Class: 10 Displaying data Age: 12 Gender: Female Output int main() { member M; staff S; stud s; cout << "Student" << endl; cout << "Enter data" << endl; s.getdata(); cout << endl << "Displaying data" << endl; s.disp(); cout << endl << "Staff Data" << endl; cout << "Enter data" << endl; S.getdata(); cout << endl << "Displaying data" << endl; S.disp(); } Staff Data Enter data Age: 12 Gender: male Salary: Rs.100000 Displaying data Age: 12 Gender: male
  • 25. Hybrid (Virtual) Inheritance ◦ Hybrid Inheritance is implemented by combining more than one type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
  • 26. Hybrid Inheritance (Continue..) // base class class Vehicle { public: Vehicle() { cout << "This is a Vehicle" << endl; } }; //base class class Fare { public: Fare() { cout<<"Fare of Vehiclen"; } }; // first sub class class Car: public Vehicle { }; // second sub class class Bus: public Vehicle, public Fare { }; This is a Vehicle Fare of Vehicle Output // main function int main() { // creating object of sub class will // invoke the constructor of base class Bus obj2; return 0; }
  • 27. Order of constructor and Destructor call ◦ Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class. If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of the derived class will be invoked but before that the default constructor of all of the base classes will be invoke, i.e the order of invokation is that the base class’s default constructor will be invoked first and then the derived class’s default constructor will be invoked.
  • 28. Order of constructor and Destructor call
  • 29. Example #include <iostream> using namespace std; // base class class Parent { public: // base class constructor Parent() { cout << "Inside base class" << endl; } }; // sub class class Child : public Parent { public: //sub class constructor Child() { cout << "Inside sub class" << endl; } }; Inside base class Inside sub class Output // main function int main() { // creating object of sub class Child obj; return 0; }
  • 30. Concept: Base class Default Constructor in Derived class Constructors! class Base { int x; public: // default constructor Base() { cout << "Base default constructorn"; } }; class Derived : public Base { int y; public: // default constructor Derived() { cout << "Derived default constructorn"; } // parameterized constructor Derived(int i) { cout << "Derived parameterized constructorn"; } Base default constructor Base default constructor Derived default constructor Base default constructor Derived parameterized constructor Output int main() { Base b; Derived d1; Derived d2(10); } Example
  • 31. Concept: Calling parameterized constructor of base class in derived class constructor! ◦ To call the parameterized constructor of base class when derived class’s parameterized constructor is called, you have to explicitly specify the base class’s parameterized constructor in derived class
  • 32. Concept: Calling parameterized constructor of base class in derived class constructor! class Base { int x; public: // parameterized constructor Base(int i) { x = i; cout << "Base Parameterized Constructorn"; } }; class Derived : public Base { int y; public: // parameterized constructor Derived(int j):Base(j) { y = j; cout << "Derived Parameterized Constructorn"; } }; Base Parameterized Constructor Derived Parameterized Constructor Output int main() { Derived d(10) ; } Example
  • 33. Important Points ◦ Whenever the derived class’s default constructor is called, the base class’s default constructor is called automatically. ◦ To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly.
  • 34. Exercise ◦ Create two classes named Mammals and MarineAnimals. Create another class named BlueWhale which inherits both the above classes. Now, create a function in each of these classes which prints "I am mammal", "I am a marine animal" and "I belong to both the categories: Mammals as well as Marine Animals" respectively. Now, create an object for each of the above class and try calling 1 - function of Mammals by the object of Mammal 2 - function of MarineAnimal by the object of MarineAnimal 3 - function of BlueWhale by the object of BlueWhale 4 - function of each of its parent by the object of BlueWhale ◦ Types of Inheritance = ?? ◦ Write a Basic Sekeletone
  • 35. Exercise ◦ Create a base class named Person with name, age, and gender as its data members. Define a constructor to initialize the data members and a function display() to display the details of the person. ◦ Create a derived class named Employee which inherits Person class. Define empid and salary as its data members. Define a constructor to initialize the data members and override the display() function to display the details of the employee. ◦ Create another derived class named Manager which inherits Employee class. Define department as its data member. Define a constructor to initialize the data members and override the display() function to display the details of the manager. ◦ Create an object for Person, Employee, and Manager classes and call their display() functions. Types of Inheritance = ?? Write a Basic Sekeletone
  • 37. Polymorphism ◦ Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and morphs means forms. So polymorphism means many forms. ◦ Polymorphism is a feature of OOPs that allows the object to behave differently in different conditions. ◦ we can define polymorphism as the ability of a message to be displayed in more than one form. ◦ First concept given by Hindley and Milner. ◦ The basic idea behind the polymorphism is that compiler does not which function to call at compile time.
  • 38. Polymorphism-contd. ◦ A real-life example of polymorphism, a person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. ◦ So the same person posses different behavior in different situations. This is called polymorphism.
  • 40. Real life example of Polymorphism Suppose if you are in class room that time you behave like a student, when you are in market at that time you behave like a customer, when you at your home at that time you behave like a son or daughter, Here one person have different-different behaviors.
  • 41. Polymorphism Importance ◦ Polymorphism saves the programmer a lot of time in re-creating code. ◦ You don't want to have to write completely different modules for every possible permutation. ◦ For example, if you had methods for tree growth, it would be hard to have to write a specific growth method for maple, spruce, pine, etc. Instead, you can have a growth function that spans across all tree types.
  • 42. Difference between Inheritance & Polymorphism S.NO INHERITANCE POLYMORPHISM 1. Inheritance is one in which a new class is created (derived class) that inherits the features from the already existing class(Base class). Whereas polymorphism is that which can be defined in multiple forms. 2. It is basically applied to classes. Whereas it is basically applied to functions or methods. 3. Inheritance supports the concept of reusability and reduces code length in object-oriented programming. Polymorphism allows the object to decide which form of the function to implement at compile-time (overloading) as well as run-time (overriding). 4. Inheritance can be single, hybrid, multiple, hierarchical and multilevel inheritance. Whereas it can be compiled-time polymorphism (overload) as well as run-time polymorphism (overriding).
  • 43. Type of Polymorphism ◦Static / Compile time polymorphism ◦Dynamic / Run time polymorphism
  • 44. Static / Compile time polymorphism ◦ It is also called Early Binding ◦ It happens where more than one methods share the same name with different parameters or signature and different return type. ◦ It is known as Early Binding because the compiler is aware of the functions with same name and also which overloaded function is to be called is known at compile time.
  • 45. Static / Compile time polymorphism using namespace std; class Geeks { public: // function with 1 int parameter void func(int x) { cout << "value of x is " << x << endl; } // function with same name but 1 double parameter void func(double x) { cout << "value of x is " << x << endl; } // function with same name and 2 int parameters void func(int x, int y) { cout << "value of x and y is " << x << ", " << y << endl; } }; int main() { Geeks obj1; // Which function is called will depend on the parameters passed // The first 'func' is called obj1.func(7); // The second 'func' is called obj1.func(9.132); // The third 'func' is called obj1.func(85,64); return 0; }
  • 46. Dynamic / Run time polymorphism ◦ This refers to the entity which changes its form depending on circumstances at runtime. ◦ Method Overriding uses runtime Polymorphism. ◦ Runtime Polymorphism is done using virtual and inheritance. ◦ It is also called Late Binding.
  • 47. Dynamic / Run time polymorphism include <bits/stdc++.h> using namespace std; class base { public: void print () { cout<< "print base class" <<endl; } void show () { cout<< "show base class" <<endl; } }; class derived:public base { public: void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly { cout<< "print derived class" <<endl; } void show () { cout<< "show derived class" <<endl; } }; //main function int main() { base *bptr; derived d; bptr = &d; //virtual function, binded at runtime (Runtime polymorphism) bptr->print(); // Non-virtual function, binded at compile time bptr->show(); return 0; }
  • 48. Virtual Function ◦ If it is necessary to use a single pointer to refer to all the different classes’ objects. This is because we will have to create a pointer to the base class that refers to all the derived objects. ◦ But, when the base class pointer contains the derived class address, the object always executes the base class function. For resolving this problem, we use the virtual function.
  • 50. The vtable for the base class is straightforward. In the case of the derived class, only function1_virtual is overridden. Hence we see that in the derived class vtable, function pointer for function1_virtual points to the overridden function in the derived class. On the other hand function pointer for function2_virtual points to a function in the base class. Thus in the above program when the base pointer is assigned a derived class object, the base pointer points to _vptr of the derived class. So when the call b->function1_virtual() is made, the function1_virtual from the derived class is called and when the function call b->function2_virtual() is made, as this function pointer points to the base class function, the base class function is called.
  • 51. Case-Study ◦ Define a class batsman with the following specifications: Private members: bcode 4 digits code number bname 20 characters innings, notout, runs integer type batavg it is calculated according to the formula – batavg =runs/(innings-notout) calcavg() Function to compute batavg Public members: readdata() Function to accept value from bcode, name, innings, notout and invoke the function calcavg() displaydata() Function to display the data members on the screen.