SlideShare uma empresa Scribd logo
1 de 41
Inheritance
Speaker: Muhammad Hammad Waseem
m.hammad.wasim@gmail.com
Inheritance
• Inheritance: The mechanism by which one class can inherit the
properties of another.
• Inheritance: A parent-child relationship between classes
• Inheritance allows sharing of the behavior of the parent class into its
child classes.
• child class can add new behavior or override existing behavior from parent
• It allows a hierarchy of classes to be built, moving from the most
general to the most specific.
• Eg: point -> 3D_point -> sphere…
Base Class, Derived Class
• Base Class
• Terms to describe the parent in the relationship, which shares its functionality
• Also called Superclass, Parent class
• Derived Class
• Terms to describe the child in the relationship, which accepts functionality
from its parent
• Also called Subclass, Child class
• General Syntax:
• class derivedClassName : AccessSpecifier
baseClassName{… … …}
Example: Base Class
class base
{
int x;
public:
void setx(int n)
{ x = n; }
void showx()
{ cout << x << ‘n’ }
};
Example: Derived Class
// Inherit as public
class derived : public base {
int y;
public:
void sety(int n)
{ y = n; }
void showy()
{ cout << y << ‘n’;}
};
Access Specifier: public
• The keyword public tells the compiler that base will be
inherited such that:
• all public members of the base class will also be public members
of derived.
• However, all private elements of base will remain private to
it and are not directly accessible by derived.
Example: main()
int main()
{
derived ob;
ob.setx(10);
ob.sety(20);
ob.showx();
ob.showy();
}
An Incorrect Example
class derived : public base {
int y;
public:
void sety(int n) { y = n; }
/* Error ! Cannot access x, which is
private member of base. */
void show_sum() {cout << x+y; }
};
Access Specifier: private
• If the access specifier is private:
• public members of base become private members of
derived.
• these members are still accessible by member functions
of derived.
Example: Derived Class
// Inherit as private
class derived : private base {
int y;
public:
void sety(int n) { y = n; }
void showy() { cout << y << ‘n’;}
};
Example: main()
int main() {
derived ob;
ob.setx(10); // Error! setx() is private.
ob.sety(20); // OK!
ob.showx(); // Error! showx() is private.
ob.showy(); // OK!
}
Example: Derived Class
class derived : private base {
int y;
public:
// setx is accessible from within derived
void setxy(int n, int m) { setx(n); y = m; }
// showx is also accessible
void showxy() { showx(); cout<<y<< ‘n’;}
};
Protected Members
• Sometimes you want to do the following:
• keep a member of a base class private
• allow a derived class access to it
• Use protected members!
• If no derived class, protected members is the same as private
members.
Protected Members
The full general form of a class declaration:
class class-name {
// private members
protected:
// protected members
public:
// public members
};
3 Types of Access Specifiers
• Type 1: Inherit as Private
Base Derived
Private members Inaccessible
Protected members Private members
Public members Private members
3 Types of Access Specifiers
• Type 2: Inherit as Protected
Base Derived
Private members Inaccessible
Protected members Protected members
Public members Protected members
3 Types of Access Specifiers
• Type 3: Inherit as Public
Base Derived
Private members Inaccessible
Protected members Protected members
Public members Public members
Constructor and Destructor
• It is possible for both the base class and the derived class to have
constructor and/or destructor functions.
• The constructor functions are executed in order of derivation.
• i.e. the base class constructor is executed first.
• The destructor functions are executed in reverse order.
Passing arguments
• What if the constructor functions of both the base class and
derived class take arguments?
1. Pass all necessary arguments to the derived class’s constructor.
2. Then pass the appropriate arguments along to the base class.
Example: Constructor of base
class base {
int i;
public:
base(int n) {
cout << “constructing base n”;
i = n; }
~base() { cout << “destructing base n”; }
};
Example: Constructor of derived
class derived : public base {
int j;
public:
derived (int n, int m) : base (m) {
cout << “constructing derivedn”;
j = n; }
~derived() { cout << “destructing derivedn”;}
};
Example: main()
int main() {
derived o(10,20);
return 0;
}
OUTPUT:
constructing base
constructing derived
destructing derived
destructing base
Multiple Inheritance
• Type 1:
Base 1
derived 1
derived 2
base 1 base 2
derived
Multiple Inheritance
• Type 2:
Example: Type 2 (first base class)
// Create first base class
class B1 {
int a;
public:
B1(int x) { a = x; }
int geta() { return a; }
};
Example: Type 2 (second base class)
// Create second base class
class B2 {
int b;
public:
B2(int x) { b = x; }
int getb() { return b; }
};
Example: Type 2 (inherit two base classes)
// Directly inherit two base classes.
class D : public B1, public B2 {
int c;
public:
D(int x, int y, int z) : B1(z), B2(y) {
c = x; }
void show() {
cout << geta() << getb() << c;}
} ;
Potential Problem
• Base is inherited twice by Derived 3!
Derived 3
Base Base
Derived 1 Derived 2
Virtual Base Class
• To resolve this problem, virtual base class can be used.
class base {
public:
int i;
};
Virtual Base Class
// Inherit base as virtual
class D1 : virtual public base {
public:
int j;
};
class D2 : virtual public base {
public:
int k;
};
Virtual Base Class
/* Here, D3 inherits both D1 and D2.
However, only one copy of base is present */
class D3 : public D1, public D2 {
public:
int product () { return i * j * k; }
};
Pointers to Derived Classes
• A pointer declared as a pointer to base class can also be used to point
to any class derived from that base.
• However, only those members of the derived object that were
inherited from the base can be accessed.
Example
base *p; // base class pointer
base B_obj;
derived D_obj;
p = &B_obj; // p can point to base object
p = &D_obj; // p can also point to derived object
Virtual Function
• A virtual function is a member function
• declared within a base class
• redefined by a derived class (i.e. overriding)
• It can be used to support run-time polymorphism.
Example
class base {
public:
int i;
base (int x) { i = x; }
virtual void func() {cout << i; }
};
Example
class derived : public base {
public:
derived (int x) : base (x) {}
// The keyword virtual is not needed.
void func() {cout << i * i; }
};
Example
int main() {
base ob(10), *p;
derived d_ob(10);
p = &ob;
p->func(); // use base’s func()
p = &d_ob;
p->func(); // use derived’s func()
}
Pure Virtual Functions
• A pure virtual function has no definition relative to the base class.
• Only the function’s prototype is included.
• General form:
virtual type func-name(paremeter-list) = 0
Example: area
class area {
public:
double dim1, dim2;
area(double x, double y)
{dim1 = x; dim2 = y;}
// pure virtual function
virtual double getarea() = 0;
};
Example: rectangle
class rectangle : public area {
public:
// function overriding
double getarea() {
return dim1 * dim2;
}
};
Example: triangle
class triangle : public area {
public:
// function overriding
double getarea() {
return 0.5 * dim1 * dim2;
}
};

Mais conteúdo relacionado

Mais procurados

Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
Kamal Acharya
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 

Mais procurados (20)

C Structures And Unions
C  Structures And  UnionsC  Structures And  Unions
C Structures And Unions
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Object oriented programming With C#
Object oriented programming With C#Object oriented programming With C#
Object oriented programming With C#
 
This pointer
This pointerThis pointer
This pointer
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Methods and constructors in java
Methods and constructors in javaMethods and constructors in java
Methods and constructors in java
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Exception handling in plsql
Exception handling in plsqlException handling in plsql
Exception handling in plsql
 
Lect 1-class and object
Lect 1-class and objectLect 1-class and object
Lect 1-class and object
 
Friend Function
Friend FunctionFriend Function
Friend Function
 
Constructor and Destructor
Constructor and DestructorConstructor and Destructor
Constructor and Destructor
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
Best Practices in Qt Quick/QML - Part 3
Best Practices in Qt Quick/QML - Part 3Best Practices in Qt Quick/QML - Part 3
Best Practices in Qt Quick/QML - Part 3
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 

Destaque

C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three nos
krismishra
 

Destaque (20)

Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]Data Structures - Lecture 3 [Arrays]
Data Structures - Lecture 3 [Arrays]
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
 
[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Arrays Data Structure
Arrays Data StructureArrays Data Structure
Arrays Data Structure
 
Computer Software & its Types
Computer Software & its Types Computer Software & its Types
Computer Software & its Types
 
C++ largest no between three nos
C++ largest no between three nosC++ largest no between three nos
C++ largest no between three nos
 
(Ooad)mirza adil
(Ooad)mirza adil(Ooad)mirza adil
(Ooad)mirza adil
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
 
[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms
 
Arrays
ArraysArrays
Arrays
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 

Semelhante a [OOP - Lec 20,21] Inheritance

INHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM.pptx
INHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM.pptxINHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM.pptx
INHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM.pptx
DeepasCSE
 
Chapter26 inheritance-ii
Chapter26 inheritance-iiChapter26 inheritance-ii
Chapter26 inheritance-ii
Deepak Singh
 

Semelhante a [OOP - Lec 20,21] Inheritance (20)

Lab3
Lab3Lab3
Lab3
 
Inheritance
InheritanceInheritance
Inheritance
 
INHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM.pptx
INHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM.pptxINHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM.pptx
INHERITANCE, POINTERS, VIRTUAL FUNCTIONS, POLYMORPHISM.pptx
 
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
 
chapter-10-inheritance.pdf
chapter-10-inheritance.pdfchapter-10-inheritance.pdf
chapter-10-inheritance.pdf
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
Inheritance
InheritanceInheritance
Inheritance
 
OOP
OOPOOP
OOP
 
Lecturespecial
LecturespecialLecturespecial
Lecturespecial
 
inheritance
   inheritance   inheritance
inheritance
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.ppt
 
29csharp
29csharp29csharp
29csharp
 
29c
29c29c
29c
 
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
 
Chapter26 inheritance-ii
Chapter26 inheritance-iiChapter26 inheritance-ii
Chapter26 inheritance-ii
 
Inheritance
InheritanceInheritance
Inheritance
 
Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)Lecture 4.2 c++(comlete reference book)
Lecture 4.2 c++(comlete reference book)
 
session 24_Inheritance.ppt
session 24_Inheritance.pptsession 24_Inheritance.ppt
session 24_Inheritance.ppt
 

Mais de Muhammad Hammad Waseem

Mais de Muhammad Hammad Waseem (19)

[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++
 
[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types[ITP - Lecture 15] Arrays & its Types
[ITP - Lecture 15] Arrays & its Types
 
[ITP - Lecture 14] Recursion
[ITP - Lecture 14] Recursion[ITP - Lecture 14] Recursion
[ITP - Lecture 14] Recursion
 
[ITP - Lecture 13] Introduction to Pointers
[ITP - Lecture 13] Introduction to Pointers[ITP - Lecture 13] Introduction to Pointers
[ITP - Lecture 13] Introduction to Pointers
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++[ITP - Lecture 11] Loops in C/C++
[ITP - Lecture 11] Loops in C/C++
 
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
 
[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)
 
[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
 
[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes
 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++
 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
 
[OOP - Lec 02] Why do we need OOP
[OOP - Lec 02] Why do we need OOP[OOP - Lec 02] Why do we need OOP
[OOP - Lec 02] Why do we need OOP
 
Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]
 

Último

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Último (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 

[OOP - Lec 20,21] Inheritance

  • 1. Inheritance Speaker: Muhammad Hammad Waseem m.hammad.wasim@gmail.com
  • 2. Inheritance • Inheritance: The mechanism by which one class can inherit the properties of another. • Inheritance: A parent-child relationship between classes • Inheritance allows sharing of the behavior of the parent class into its child classes. • child class can add new behavior or override existing behavior from parent • It allows a hierarchy of classes to be built, moving from the most general to the most specific. • Eg: point -> 3D_point -> sphere…
  • 3. Base Class, Derived Class • Base Class • Terms to describe the parent in the relationship, which shares its functionality • Also called Superclass, Parent class • Derived Class • Terms to describe the child in the relationship, which accepts functionality from its parent • Also called Subclass, Child class • General Syntax: • class derivedClassName : AccessSpecifier baseClassName{… … …}
  • 4. Example: Base Class class base { int x; public: void setx(int n) { x = n; } void showx() { cout << x << ‘n’ } };
  • 5. Example: Derived Class // Inherit as public class derived : public base { int y; public: void sety(int n) { y = n; } void showy() { cout << y << ‘n’;} };
  • 6. Access Specifier: public • The keyword public tells the compiler that base will be inherited such that: • all public members of the base class will also be public members of derived. • However, all private elements of base will remain private to it and are not directly accessible by derived.
  • 7. Example: main() int main() { derived ob; ob.setx(10); ob.sety(20); ob.showx(); ob.showy(); }
  • 8. An Incorrect Example class derived : public base { int y; public: void sety(int n) { y = n; } /* Error ! Cannot access x, which is private member of base. */ void show_sum() {cout << x+y; } };
  • 9. Access Specifier: private • If the access specifier is private: • public members of base become private members of derived. • these members are still accessible by member functions of derived.
  • 10. Example: Derived Class // Inherit as private class derived : private base { int y; public: void sety(int n) { y = n; } void showy() { cout << y << ‘n’;} };
  • 11. Example: main() int main() { derived ob; ob.setx(10); // Error! setx() is private. ob.sety(20); // OK! ob.showx(); // Error! showx() is private. ob.showy(); // OK! }
  • 12. Example: Derived Class class derived : private base { int y; public: // setx is accessible from within derived void setxy(int n, int m) { setx(n); y = m; } // showx is also accessible void showxy() { showx(); cout<<y<< ‘n’;} };
  • 13. Protected Members • Sometimes you want to do the following: • keep a member of a base class private • allow a derived class access to it • Use protected members! • If no derived class, protected members is the same as private members.
  • 14. Protected Members The full general form of a class declaration: class class-name { // private members protected: // protected members public: // public members };
  • 15. 3 Types of Access Specifiers • Type 1: Inherit as Private Base Derived Private members Inaccessible Protected members Private members Public members Private members
  • 16. 3 Types of Access Specifiers • Type 2: Inherit as Protected Base Derived Private members Inaccessible Protected members Protected members Public members Protected members
  • 17. 3 Types of Access Specifiers • Type 3: Inherit as Public Base Derived Private members Inaccessible Protected members Protected members Public members Public members
  • 18. Constructor and Destructor • It is possible for both the base class and the derived class to have constructor and/or destructor functions. • The constructor functions are executed in order of derivation. • i.e. the base class constructor is executed first. • The destructor functions are executed in reverse order.
  • 19. Passing arguments • What if the constructor functions of both the base class and derived class take arguments? 1. Pass all necessary arguments to the derived class’s constructor. 2. Then pass the appropriate arguments along to the base class.
  • 20. Example: Constructor of base class base { int i; public: base(int n) { cout << “constructing base n”; i = n; } ~base() { cout << “destructing base n”; } };
  • 21. Example: Constructor of derived class derived : public base { int j; public: derived (int n, int m) : base (m) { cout << “constructing derivedn”; j = n; } ~derived() { cout << “destructing derivedn”;} };
  • 22. Example: main() int main() { derived o(10,20); return 0; } OUTPUT: constructing base constructing derived destructing derived destructing base
  • 23. Multiple Inheritance • Type 1: Base 1 derived 1 derived 2
  • 24. base 1 base 2 derived Multiple Inheritance • Type 2:
  • 25. Example: Type 2 (first base class) // Create first base class class B1 { int a; public: B1(int x) { a = x; } int geta() { return a; } };
  • 26. Example: Type 2 (second base class) // Create second base class class B2 { int b; public: B2(int x) { b = x; } int getb() { return b; } };
  • 27. Example: Type 2 (inherit two base classes) // Directly inherit two base classes. class D : public B1, public B2 { int c; public: D(int x, int y, int z) : B1(z), B2(y) { c = x; } void show() { cout << geta() << getb() << c;} } ;
  • 28. Potential Problem • Base is inherited twice by Derived 3! Derived 3 Base Base Derived 1 Derived 2
  • 29. Virtual Base Class • To resolve this problem, virtual base class can be used. class base { public: int i; };
  • 30. Virtual Base Class // Inherit base as virtual class D1 : virtual public base { public: int j; }; class D2 : virtual public base { public: int k; };
  • 31. Virtual Base Class /* Here, D3 inherits both D1 and D2. However, only one copy of base is present */ class D3 : public D1, public D2 { public: int product () { return i * j * k; } };
  • 32. Pointers to Derived Classes • A pointer declared as a pointer to base class can also be used to point to any class derived from that base. • However, only those members of the derived object that were inherited from the base can be accessed.
  • 33. Example base *p; // base class pointer base B_obj; derived D_obj; p = &B_obj; // p can point to base object p = &D_obj; // p can also point to derived object
  • 34. Virtual Function • A virtual function is a member function • declared within a base class • redefined by a derived class (i.e. overriding) • It can be used to support run-time polymorphism.
  • 35. Example class base { public: int i; base (int x) { i = x; } virtual void func() {cout << i; } };
  • 36. Example class derived : public base { public: derived (int x) : base (x) {} // The keyword virtual is not needed. void func() {cout << i * i; } };
  • 37. Example int main() { base ob(10), *p; derived d_ob(10); p = &ob; p->func(); // use base’s func() p = &d_ob; p->func(); // use derived’s func() }
  • 38. Pure Virtual Functions • A pure virtual function has no definition relative to the base class. • Only the function’s prototype is included. • General form: virtual type func-name(paremeter-list) = 0
  • 39. Example: area class area { public: double dim1, dim2; area(double x, double y) {dim1 = x; dim2 = y;} // pure virtual function virtual double getarea() = 0; };
  • 40. Example: rectangle class rectangle : public area { public: // function overriding double getarea() { return dim1 * dim2; } };
  • 41. Example: triangle class triangle : public area { public: // function overriding double getarea() { return 0.5 * dim1 * dim2; } };