SlideShare a Scribd company logo
Course:Course:
Object Oriented ProgrammingObject Oriented Programming
4.00 Credit Hours, Spring 2014,4.00 Credit Hours, Spring 2014,
Undergraduate ProgramUndergraduate Program
Instructor: Sabeen JavaidInstructor: Sabeen Javaid
SESSION 1, 2SESSION 1, 2
InheritanceInheritance
InheritanceInheritance
Inheritance is a relationship between two
or more classes where derived class
inherits behaviour and attributes of pre-
existing (base) classes
Intended to help reuse of existing code
with little or no modification
2
InheritanceInheritance
The existing class is called the base class,
and the new class is called the derived
class.
Other programming languages, such as Java
and C#, refer to the base class as the
superclass
and the derived class as the subclass. A
derived class represents a more specialized
group of objects.
3
InheritanceInheritance
It is expressed in C++ by the “ : public “
syntax:
◦ class Car : public Vehicle {};
Car “is a” / “is derived from” / “is a
specialized” / “is a subclass of” / “is a
derived class of” Vehicle
Vehicle “is a base class of” / “is a super
class of” Car
4
Inheritance - ExampleInheritance - Example
5
Inheritance - ExampleInheritance - Example
6
Inheritance: is-A RelationshipInheritance: is-A Relationship
Derived class objects can always be treated
like a base class objects
Example: an object of type Student can
always be used like an object of type Person
◦ Especially, we can call all methods of Person on
an object of type Student
7
InheritanceInheritance
• Inheritance can be continuous
–Derived class can inherit from a base class
–The derived class can act as a base class and
another class can inherit from it
–If you change the base class, all derived classes
also change
–Any changes in the derived class do not change
the base class
–All features of the base class are available in the
derived class
• However, the additional features in the derived class
are not available in the base class
8
9
Base Classes and Derived Classes
10
CommunityMember Class Hierarchy
11
Shape Class Hierarchy
12
Inheritance
a
b
Class A
Features: a,b
c
Class B
Features: a,b,c
d
e
Class C
Features: a,b,d,e
f
Class D
Features: a,b,d,e,f
Inheritance and EncapsulationInheritance and Encapsulation
Three levels of access control
◦ Public: members (data and methods) can be
used by the class and everybody else (other
classes, functions, etc.)
◦ Protected: members can be accessed by the
class (and its friends) and its derived classes
◦ Private: members can be accessed only by the
class (and its friends)
Remark: without inheritance private and
protected are the same
Inheritance and EncapsulationInheritance and Encapsulation
• private member
– Is accessible only via the base class
• public member
– Is accessible everywhere (base class, derived
class, other classes)
• protected member
– Is accessible by the base class and derived classes
15
Inheritance Concept
Rectangle
Triangle
Polygon
class Polygon
{
private:
int width, length;
public:
void set(int w, int
l);
};
class Rectangle{
private:
int width, length;
public:
void set(int w, int
l);
int area();
};
class Triangle{
private:
int width, length;
public:
void set(int w, int
l);
int area();
};
16
Rectangle
Triangle
Polygon
class Polygon
{
protected:
int width, length;
public:
void set(int w, int
l);
};
class Rectangle: public
Polygon
{
public:
int area();
};
class Rectangle{
protected:
int width, length;
public:
void set(int w, int
l);
int area();
Inheritance Concept
17
Rectangle
Triangle
Polygon
class Polygon
{
protected:
int width, length;
public:
void set(int w, int
l);
};
class Triangle :
public Polygon
{
public:
int area();
};
class Triangle{
protected:
int width, length;
public:
void set(int w, int
l);
int area();
Inheritance Concept
18
Inheritance Concept
Point
Circle 3D-Point
class Point
{
protected:
int x, y;
public:
void set(int a, int
b);
};
class Circle : public Point
{
private:
double r;
};
class 3D-Point: public Point
{
private:
int z;
};
x
y
x
y
r
x
y
z
class DerivedClassName : access-level BaseClassName
Declaring InheritanceDeclaring Inheritance
• Syntax:
where
–access-level specifies the type of derivation
• private by default, or
• public or
• protected (used very rarely)
• Any class can serve as a base class
–Thus a derived class can also be a base class
19
20
Class Derivation
Point
3D-Point
class Point{
protected:
int x, y;
public:
void set(int a,
int b);
};
class 3D-Point :
public Point{
private: double
z;
… …
};
class Sphere : public
3D-Point{
private: double r;
… …
};
Sphere
Point is the base class of 3D-Point, while 3D-Point is the base class of
Sphere
What to Inherit?What to Inherit?
In principle, every member of a base class
is inherited by a derived class
◦ just with different access permission
21
22
Access Control Over the Members
• Two levels of access control over
class members
– class definition
– inheritance type
class Point{
protected: int x, y;
public: void set(int
a, int b);
};
class Circle : public
Point{
… …
};
Member Access ControlMember Access Control
 There are 3 levels of member (data or methods) access control:
◦ public: members can be used by itself and the whole world; any
function can access them
◦ protected: methods (and friends) of itself and any derived class can
use it
◦ private: members can only be used by its own methods (and its
friends)
 We’ll study friend functions later
 Without inheritance, private and protected have the same
meaning
 The only difference is that methods of a derived class can access
protected members of a base class, but cannot access private
members of a base class
23
24
Access Rights of Derived ClassesAccess Rights of Derived Classes
• Public inheritance preserves the original accessibility
of the base class public and protected members in the
derived class
– (base) public -> (derived) public
– (base) protected -> (derived) protected
– (base) private -> no access
• Protected inheritance causes public members to
become protected (protected members are preserved)
in the derived class
– (base) public -> (derived) protected
– (base) protected -> (derived) protected
– (base) private -> no access
25
Access Rights of Derived ClassesAccess Rights of Derived Classes
• Private inheritance causes all members to become
private in the derived class
– (base) public -> (derived) private
– (base) protected -> (derived) private
– (base) private -> no access
Access Rights of Derived Classes -Access Rights of Derived Classes -
SummarySummary
 The type of inheritance defines the minimum access level for the
members of derived class that are inherited from the base class
 With public inheritance, the derived class follows the same access
permission as in the base class
 With protected inheritance, only the public members inherited from
the base class can be accessed in the derived class as protected
members
 With private inheritance, all members from the base class are inherited
as private. This means private members stay private, and protected and
public members become private.
private protected public
private private private private
protected private protected protected
public private protected public
Type of Inheritance
AccessControl
forMembers
Access Rights of Derived ClassesAccess Rights of Derived Classes
 Take these classes as examples:
  class B                    { /*...*/ };
 class D_priv : private   B { /*...*/ };
 class D_prot : protected B { /*...*/ };
 class D_publ : public    B { /*...*/ };
 class UserClass          { B b; /*...*/ 
}; 
 None of the derived classes can access anything that is private in B
 In D_priv, the public and protected parts of B are private
 In D_prot, the public and protected parts of B are protected
 In D_publ, the public parts of B are public and the protected parts
of B are protected (D_publ is-a-kind-of-a B)
 class UserClass can access only the public parts of B, which "seals
off" UserClass from B
27
28
protected vs. private
So why not always use protected instead of private?
– Because protected means that we have less encapsulation
– All derived classes can access protected data members of the
base class
– Assume that later you decided to change the implementation of
the base class having the protected data members
– For example, we might want to represent address by a new
class called Address instead of string
– If the address data member is private, we can easily make this
change
– The class documentation does not need to be changed.
– If it is protected, we have to go through all derived classes and
change them
– We also need to update the class documentation.
29
When to use Private InheritanceWhen to use Private Inheritance
• Overall private and protected inheritance are used very
rarely
• Private and protected inheritance are used to represent
implementation details
• Protected bases are useful in class hierarchies in which
further derivation is needed
• Private bases are useful when defining a class by
restricting the interface to a base so that stronger
guarantees can be provided
30
Class Derivation Example
mother
daughter son
class mother{
protected:
   int x, y;
public:
  void set(int a, 
int b);
private:
   int z;
};
class daughter : 
public mother{
private: 
double a;
public:
void foo ( );
};
void daughter :: foo ( ){
x = y = 20;
set(5, 10); 
cout<<“value of a 
”<<a<<endl; 
z = 100;    // error, a 
private member
};
daughter can access 3 of the 4 inherited members
Class DerivationClass Derivation
mother
daughter son
class mother{
protected:
int x, y;
public:
void set(int a, int b);
private:
int z;
}
class son : protected mother{
private:
double b;
public:
void foo ( );
}
void son :: foo ( ){
x = y = 20;
set(5, 10);
cout<<“value of b ”<<b<<endl;
z = 100; // error, not a public
member
}
son can access only 3 of the 4 inherited member
32
mother
daughter son
granddaughter grandson
Class Derivation Example
class mother{
protected:
   int x, y;
public:
  void set(int a, 
int b);
private:
   int z;
};
class daughter : public mother
{
private: 
double a;
public:
void foo ( );
};
class granddaughter : public daughter
{
public:
void foo ( );
};
33
void granddaughter :: foo ( ){
x = y = 20; //OK
set(5, 10);  //OK
cout<<“value of a ”<<a<<endl; //error: private 
member of daughter
z = 100;    // error, a private member of mother
};
Class Derivation Example
34
mother
daughter son
granddaughter grandson
class mother{
protected:
int x, y;
public:
void set(int a,
int b);
private:
int z;
};
class son : protected mother
{
private:
double b;
public:
void foo ( );
};
class grandson : public son
{
public:
void foo ( );
};
Class Derivation Example
35
void grandson:: foo ( ){
x = y = 20;
set(5, 10);
z = 100; // error, a private member of
mother
};
Class Derivation Example
EncapsulationEncapsulation
class Figure
{
protected:
int x, y;
};
class Circle : public Figure
{
public:
int radius;
};
int main()
{
Circle a;
a.x = 0;
a.y = 0;
a.radius = 10;
}
EncapsulationEncapsulation
class Figure
{
protected:
int x_, y_;
};
class Circle : public
Figure
{
private:
int radius_;
public:
Circle(int x,
int y, int radius);
};
Circle::Circle(int x,
int y, int radius)
{
x_ = x;
y_ = y;
radius_ = radius;
}
int main()
{
Circle a(0,0,10);
}
EncapsulationEncapsulation
class Figure
{
private:
int x_, y_;
};
class Circle : public
Figure
{
private:
int radius_;
public:
Circle(int x,
int y, int radius);
};
Circle::Circle(int x,
int y, int radius)
{
x_ = x;
y_ = y;
radius_ = radius;
}
int main()
{
Circle a(0,0,10);
}
EncapsulationEncapsulation
class Figure
{
private:
int x_, y_;
public:
void SetX(int
x);
void SetY(int
y);
};
void Figure::SetX(int
x)
{
x_ = x;
}
void Figure::SetY(int
y)
{
y_ = y;
class Circle : public
Figure
{
private:
int radius_;
public:
Circle(int x, int
y, int radius);
};
Circle::Circle(int x,
int y, int radius)
{
SetX(x);
SetY(y);
radius_ = radius;
}
int main()
{
Circle a(0,0,10);
}
What to Inherit?What to Inherit?
In principle, every member of a base class
is inherited by a derived class
◦ just with different access permission
However, there are exceptions for
◦ Constructor and destructor
◦ Overloaded Assignment operator
◦ Friends
Since all these functions are class-specific!
40
References/ Compulsory ReadingReferences/ Compulsory Reading
C++, How to Program Deitel & Deitel
◦ Chapter 12: OOP : Inheritance
Robert Lafore
◦ Chapter 9: Inheritance
◦ http://www.learncpp.com/cpp-tutorial/115-inheri
41

More Related Content

What's hot (20)

OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
Thooyavan Venkatachalam
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Paumil Patel
 
Inheritance in Object Oriented Programming
Inheritance in Object Oriented ProgrammingInheritance in Object Oriented Programming
Inheritance in Object Oriented Programming
Ashita Agrawal
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classes
asadsardar
 
Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)
Gajendra Singh Thakur
 
inheritance
inheritanceinheritance
inheritance
Nivetha Elangovan
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
Arnab Bhaumik
 
Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++
Sujan Mia
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Single inheritance
Single inheritanceSingle inheritance
Single inheritance
Äkshäý M S
 
Inheritance
InheritanceInheritance
Inheritance
poonam.rwalia
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
Prem Kumar Badri
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Abstract class
Abstract classAbstract class
Abstract class
Tony Nguyen
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vineeta Garg
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
Abhilash Nair
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
Hirra Sultan
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Paumil Patel
 
Inheritance in Object Oriented Programming
Inheritance in Object Oriented ProgrammingInheritance in Object Oriented Programming
Inheritance in Object Oriented Programming
Ashita Agrawal
 
Friends function and_classes
Friends function and_classesFriends function and_classes
Friends function and_classes
asadsardar
 
Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)Inheritance In C++ (Object Oriented Programming)
Inheritance In C++ (Object Oriented Programming)
Gajendra Singh Thakur
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
Tareq Hasan
 
Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++
Sujan Mia
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vineeta Garg
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
Abhilash Nair
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
Hirra Sultan
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 

Viewers also liked (20)

Inheritance
InheritanceInheritance
Inheritance
Sapna Sharma
 
Oops ppt
Oops pptOops ppt
Oops ppt
abhayjuneja
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
BG Java EE Course
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
Oum Saokosal
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
Muraleedhar Sundararajan
 
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...
cprogrammings
 
Constructors & destructors
Constructors & destructorsConstructors & destructors
Constructors & destructors
ForwardBlog Enewzletter
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
Adil Kakakhel
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
Jussi Pohjolainen
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
Terry Yoast
 
Hybrid Inheritance in C++
Hybrid Inheritance in C++Hybrid Inheritance in C++
Hybrid Inheritance in C++
Abhishek Pratap
 
Automation patterns on practice
Automation patterns on practiceAutomation patterns on practice
Automation patterns on practice
automated-testing.info
 
Архитектура автоматизированных тестов
Архитектура автоматизированных тестовАрхитектура автоматизированных тестов
Архитектура автоматизированных тестов
SQALab
 
Demultiplexer presentation
Demultiplexer presentationDemultiplexer presentation
Demultiplexer presentation
Shaikat Saha
 
INPUT BOX- VBA
INPUT BOX- VBAINPUT BOX- VBA
INPUT BOX- VBA
ViVek Patel
 
Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming concepts
rahuld115
 
Debugging
DebuggingDebugging
Debugging
nicky_walters
 
Dotnet framework
Dotnet frameworkDotnet framework
Dotnet framework
Nitu Pandey
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Java Programming - Inheritance
Java Programming - InheritanceJava Programming - Inheritance
Java Programming - Inheritance
Oum Saokosal
 
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...
cprogrammings
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
Adil Kakakhel
 
Hybrid Inheritance in C++
Hybrid Inheritance in C++Hybrid Inheritance in C++
Hybrid Inheritance in C++
Abhishek Pratap
 
Архитектура автоматизированных тестов
Архитектура автоматизированных тестовАрхитектура автоматизированных тестов
Архитектура автоматизированных тестов
SQALab
 
Demultiplexer presentation
Demultiplexer presentationDemultiplexer presentation
Demultiplexer presentation
Shaikat Saha
 
Object oriented programming concepts
Object oriented programming conceptsObject oriented programming concepts
Object oriented programming concepts
rahuld115
 
Dotnet framework
Dotnet frameworkDotnet framework
Dotnet framework
Nitu Pandey
 
Ad

Similar to Inheritance, Object Oriented Programming (20)

11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
LadallaRajKumar
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
RAJ KUMAR
 
Introduction to Inheritance
Introduction to InheritanceIntroduction to Inheritance
Introduction to Inheritance
Keshav Vaswani
 
Inheritance
InheritanceInheritance
Inheritance
Munsif Ullah
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
Shweta Shah
 
MODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computerMODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computer
ssuser6f3c8a
 
inheritance
inheritanceinheritance
inheritance
Amir_Mukhtar
 
session 24_Inheritance.ppt
session 24_Inheritance.pptsession 24_Inheritance.ppt
session 24_Inheritance.ppt
NAVANEETCHATURVEDI2
 
week14 (1).ppt
week14 (1).pptweek14 (1).ppt
week14 (1).ppt
amal68766
 
Lecture 5.mte 407
Lecture 5.mte 407Lecture 5.mte 407
Lecture 5.mte 407
rumanatasnim415
 
Chapter25 inheritance-i
Chapter25 inheritance-iChapter25 inheritance-i
Chapter25 inheritance-i
Deepak Singh
 
Overview of Object Oriented Programming using C++
Overview of Object Oriented Programming using C++Overview of Object Oriented Programming using C++
Overview of Object Oriented Programming using C++
jayanthi699330
 
Object oriented programming new syllabus presentation
Object oriented programming new syllabus presentationObject oriented programming new syllabus presentation
Object oriented programming new syllabus presentation
iqraamjad1405
 
Inheritance
InheritanceInheritance
Inheritance
pooja_doshi
 
Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.
MASQ Technologies
 
EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++
Nikunj Patel
 
inheritance_OOPC_datastream.ppttttttttttttttx
inheritance_OOPC_datastream.ppttttttttttttttxinheritance_OOPC_datastream.ppttttttttttttttx
inheritance_OOPC_datastream.ppttttttttttttttx
SanskritiGupta39
 
OOP
OOPOOP
OOP
karan saini
 
Lecturespecial
LecturespecialLecturespecial
Lecturespecial
karan saini
 
B.sc CSIT 2nd semester C++ Unit5
B.sc CSIT  2nd semester C++ Unit5B.sc CSIT  2nd semester C++ Unit5
B.sc CSIT 2nd semester C++ Unit5
Tekendra Nath Yogi
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
RAJ KUMAR
 
Introduction to Inheritance
Introduction to InheritanceIntroduction to Inheritance
Introduction to Inheritance
Keshav Vaswani
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
Shweta Shah
 
MODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computerMODULE2_INHERITANCE_SESSION1.ppt computer
MODULE2_INHERITANCE_SESSION1.ppt computer
ssuser6f3c8a
 
week14 (1).ppt
week14 (1).pptweek14 (1).ppt
week14 (1).ppt
amal68766
 
Chapter25 inheritance-i
Chapter25 inheritance-iChapter25 inheritance-i
Chapter25 inheritance-i
Deepak Singh
 
Overview of Object Oriented Programming using C++
Overview of Object Oriented Programming using C++Overview of Object Oriented Programming using C++
Overview of Object Oriented Programming using C++
jayanthi699330
 
Object oriented programming new syllabus presentation
Object oriented programming new syllabus presentationObject oriented programming new syllabus presentation
Object oriented programming new syllabus presentation
iqraamjad1405
 
Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.Inheritance OOP Concept in C++.
Inheritance OOP Concept in C++.
MASQ Technologies
 
EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++EASY TO LEARN INHERITANCE IN C++
EASY TO LEARN INHERITANCE IN C++
Nikunj Patel
 
inheritance_OOPC_datastream.ppttttttttttttttx
inheritance_OOPC_datastream.ppttttttttttttttxinheritance_OOPC_datastream.ppttttttttttttttx
inheritance_OOPC_datastream.ppttttttttttttttx
SanskritiGupta39
 
B.sc CSIT 2nd semester C++ Unit5
B.sc CSIT  2nd semester C++ Unit5B.sc CSIT  2nd semester C++ Unit5
B.sc CSIT 2nd semester C++ Unit5
Tekendra Nath Yogi
 
Ad

Recently uploaded (20)

IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
AI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA TechnologiesAI and Deep Learning with NVIDIA Technologies
AI and Deep Learning with NVIDIA Technologies
SandeepKS52
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Generative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its ApplicationsGenerative Artificial Intelligence and its Applications
Generative Artificial Intelligence and its Applications
SandeepKS52
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines OperationsHow Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptxwAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 

Inheritance, Object Oriented Programming

  • 1. Course:Course: Object Oriented ProgrammingObject Oriented Programming 4.00 Credit Hours, Spring 2014,4.00 Credit Hours, Spring 2014, Undergraduate ProgramUndergraduate Program Instructor: Sabeen JavaidInstructor: Sabeen Javaid SESSION 1, 2SESSION 1, 2 InheritanceInheritance
  • 2. InheritanceInheritance Inheritance is a relationship between two or more classes where derived class inherits behaviour and attributes of pre- existing (base) classes Intended to help reuse of existing code with little or no modification 2
  • 3. InheritanceInheritance The existing class is called the base class, and the new class is called the derived class. Other programming languages, such as Java and C#, refer to the base class as the superclass and the derived class as the subclass. A derived class represents a more specialized group of objects. 3
  • 4. InheritanceInheritance It is expressed in C++ by the “ : public “ syntax: ◦ class Car : public Vehicle {}; Car “is a” / “is derived from” / “is a specialized” / “is a subclass of” / “is a derived class of” Vehicle Vehicle “is a base class of” / “is a super class of” Car 4
  • 7. Inheritance: is-A RelationshipInheritance: is-A Relationship Derived class objects can always be treated like a base class objects Example: an object of type Student can always be used like an object of type Person ◦ Especially, we can call all methods of Person on an object of type Student 7
  • 8. InheritanceInheritance • Inheritance can be continuous –Derived class can inherit from a base class –The derived class can act as a base class and another class can inherit from it –If you change the base class, all derived classes also change –Any changes in the derived class do not change the base class –All features of the base class are available in the derived class • However, the additional features in the derived class are not available in the base class 8
  • 9. 9 Base Classes and Derived Classes
  • 12. 12 Inheritance a b Class A Features: a,b c Class B Features: a,b,c d e Class C Features: a,b,d,e f Class D Features: a,b,d,e,f
  • 13. Inheritance and EncapsulationInheritance and Encapsulation Three levels of access control ◦ Public: members (data and methods) can be used by the class and everybody else (other classes, functions, etc.) ◦ Protected: members can be accessed by the class (and its friends) and its derived classes ◦ Private: members can be accessed only by the class (and its friends) Remark: without inheritance private and protected are the same
  • 14. Inheritance and EncapsulationInheritance and Encapsulation • private member – Is accessible only via the base class • public member – Is accessible everywhere (base class, derived class, other classes) • protected member – Is accessible by the base class and derived classes
  • 15. 15 Inheritance Concept Rectangle Triangle Polygon class Polygon { private: int width, length; public: void set(int w, int l); }; class Rectangle{ private: int width, length; public: void set(int w, int l); int area(); }; class Triangle{ private: int width, length; public: void set(int w, int l); int area(); };
  • 16. 16 Rectangle Triangle Polygon class Polygon { protected: int width, length; public: void set(int w, int l); }; class Rectangle: public Polygon { public: int area(); }; class Rectangle{ protected: int width, length; public: void set(int w, int l); int area(); Inheritance Concept
  • 17. 17 Rectangle Triangle Polygon class Polygon { protected: int width, length; public: void set(int w, int l); }; class Triangle : public Polygon { public: int area(); }; class Triangle{ protected: int width, length; public: void set(int w, int l); int area(); Inheritance Concept
  • 18. 18 Inheritance Concept Point Circle 3D-Point class Point { protected: int x, y; public: void set(int a, int b); }; class Circle : public Point { private: double r; }; class 3D-Point: public Point { private: int z; }; x y x y r x y z
  • 19. class DerivedClassName : access-level BaseClassName Declaring InheritanceDeclaring Inheritance • Syntax: where –access-level specifies the type of derivation • private by default, or • public or • protected (used very rarely) • Any class can serve as a base class –Thus a derived class can also be a base class 19
  • 20. 20 Class Derivation Point 3D-Point class Point{ protected: int x, y; public: void set(int a, int b); }; class 3D-Point : public Point{ private: double z; … … }; class Sphere : public 3D-Point{ private: double r; … … }; Sphere Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere
  • 21. What to Inherit?What to Inherit? In principle, every member of a base class is inherited by a derived class ◦ just with different access permission 21
  • 22. 22 Access Control Over the Members • Two levels of access control over class members – class definition – inheritance type class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ … … };
  • 23. Member Access ControlMember Access Control  There are 3 levels of member (data or methods) access control: ◦ public: members can be used by itself and the whole world; any function can access them ◦ protected: methods (and friends) of itself and any derived class can use it ◦ private: members can only be used by its own methods (and its friends)  We’ll study friend functions later  Without inheritance, private and protected have the same meaning  The only difference is that methods of a derived class can access protected members of a base class, but cannot access private members of a base class 23
  • 24. 24 Access Rights of Derived ClassesAccess Rights of Derived Classes • Public inheritance preserves the original accessibility of the base class public and protected members in the derived class – (base) public -> (derived) public – (base) protected -> (derived) protected – (base) private -> no access • Protected inheritance causes public members to become protected (protected members are preserved) in the derived class – (base) public -> (derived) protected – (base) protected -> (derived) protected – (base) private -> no access
  • 25. 25 Access Rights of Derived ClassesAccess Rights of Derived Classes • Private inheritance causes all members to become private in the derived class – (base) public -> (derived) private – (base) protected -> (derived) private – (base) private -> no access
  • 26. Access Rights of Derived Classes -Access Rights of Derived Classes - SummarySummary  The type of inheritance defines the minimum access level for the members of derived class that are inherited from the base class  With public inheritance, the derived class follows the same access permission as in the base class  With protected inheritance, only the public members inherited from the base class can be accessed in the derived class as protected members  With private inheritance, all members from the base class are inherited as private. This means private members stay private, and protected and public members become private. private protected public private private private private protected private protected protected public private protected public Type of Inheritance AccessControl forMembers
  • 27. Access Rights of Derived ClassesAccess Rights of Derived Classes  Take these classes as examples:   class B                    { /*...*/ };  class D_priv : private   B { /*...*/ };  class D_prot : protected B { /*...*/ };  class D_publ : public    B { /*...*/ };  class UserClass          { B b; /*...*/  };   None of the derived classes can access anything that is private in B  In D_priv, the public and protected parts of B are private  In D_prot, the public and protected parts of B are protected  In D_publ, the public parts of B are public and the protected parts of B are protected (D_publ is-a-kind-of-a B)  class UserClass can access only the public parts of B, which "seals off" UserClass from B 27
  • 28. 28 protected vs. private So why not always use protected instead of private? – Because protected means that we have less encapsulation – All derived classes can access protected data members of the base class – Assume that later you decided to change the implementation of the base class having the protected data members – For example, we might want to represent address by a new class called Address instead of string – If the address data member is private, we can easily make this change – The class documentation does not need to be changed. – If it is protected, we have to go through all derived classes and change them – We also need to update the class documentation.
  • 29. 29 When to use Private InheritanceWhen to use Private Inheritance • Overall private and protected inheritance are used very rarely • Private and protected inheritance are used to represent implementation details • Protected bases are useful in class hierarchies in which further derivation is needed • Private bases are useful when defining a class by restricting the interface to a base so that stronger guarantees can be provided
  • 30. 30 Class Derivation Example mother daughter son class mother{ protected:    int x, y; public:   void set(int a,  int b); private:    int z; }; class daughter :  public mother{ private:  double a; public: void foo ( ); }; void daughter :: foo ( ){ x = y = 20; set(5, 10);  cout<<“value of a  ”<<a<<endl;  z = 100;    // error, a  private member }; daughter can access 3 of the 4 inherited members
  • 31. Class DerivationClass Derivation mother daughter son class mother{ protected: int x, y; public: void set(int a, int b); private: int z; } class son : protected mother{ private: double b; public: void foo ( ); } void son :: foo ( ){ x = y = 20; set(5, 10); cout<<“value of b ”<<b<<endl; z = 100; // error, not a public member } son can access only 3 of the 4 inherited member
  • 32. 32 mother daughter son granddaughter grandson Class Derivation Example class mother{ protected:    int x, y; public:   void set(int a,  int b); private:    int z; }; class daughter : public mother { private:  double a; public: void foo ( ); }; class granddaughter : public daughter { public: void foo ( ); };
  • 34. 34 mother daughter son granddaughter grandson class mother{ protected: int x, y; public: void set(int a, int b); private: int z; }; class son : protected mother { private: double b; public: void foo ( ); }; class grandson : public son { public: void foo ( ); }; Class Derivation Example
  • 35. 35 void grandson:: foo ( ){ x = y = 20; set(5, 10); z = 100; // error, a private member of mother }; Class Derivation Example
  • 36. EncapsulationEncapsulation class Figure { protected: int x, y; }; class Circle : public Figure { public: int radius; }; int main() { Circle a; a.x = 0; a.y = 0; a.radius = 10; }
  • 37. EncapsulationEncapsulation class Figure { protected: int x_, y_; }; class Circle : public Figure { private: int radius_; public: Circle(int x, int y, int radius); }; Circle::Circle(int x, int y, int radius) { x_ = x; y_ = y; radius_ = radius; } int main() { Circle a(0,0,10); }
  • 38. EncapsulationEncapsulation class Figure { private: int x_, y_; }; class Circle : public Figure { private: int radius_; public: Circle(int x, int y, int radius); }; Circle::Circle(int x, int y, int radius) { x_ = x; y_ = y; radius_ = radius; } int main() { Circle a(0,0,10); }
  • 39. EncapsulationEncapsulation class Figure { private: int x_, y_; public: void SetX(int x); void SetY(int y); }; void Figure::SetX(int x) { x_ = x; } void Figure::SetY(int y) { y_ = y; class Circle : public Figure { private: int radius_; public: Circle(int x, int y, int radius); }; Circle::Circle(int x, int y, int radius) { SetX(x); SetY(y); radius_ = radius; } int main() { Circle a(0,0,10); }
  • 40. What to Inherit?What to Inherit? In principle, every member of a base class is inherited by a derived class ◦ just with different access permission However, there are exceptions for ◦ Constructor and destructor ◦ Overloaded Assignment operator ◦ Friends Since all these functions are class-specific! 40
  • 41. References/ Compulsory ReadingReferences/ Compulsory Reading C++, How to Program Deitel & Deitel ◦ Chapter 12: OOP : Inheritance Robert Lafore ◦ Chapter 9: Inheritance ◦ http://www.learncpp.com/cpp-tutorial/115-inheri 41