SlideShare a Scribd company logo
Inheritance
In C++
 Inheritance is a mechanism for
• building class types from other class types
• defining new class types to be a
–specialization
–augmentation
of existing types
Inheritance
Subgroupings with respect to a parent are called
– Subclass
– Derived Class
– Children
The derived class
– inherits from the parent all
• characteristics
• properties
• capabilities
– can modify or extend inherited abilities
Inheritance
VEHICLE
LANDBASED
AUTOMOBILE BICYCLE
• Consider the vehicle hierarchy:
• Note that each entity is also a class
• Classes are used in an object centered paradigm as a
means of encapsulating common data and functions
shared by members of the class
Class and Instance Hierarchy
We actually have two hierarchies
AUTOMOBILE BICYCLE
LANDBASED
VEHICLE
myAutomyBicycle
myLandBased
myVehicle
Single/Multiple Inheritance
Single Inheritance
Each class or instance object has a single parent
Multiple Inheritance
Classes inherit from multiple base classes ( might not have same
ancestors as shown in the example below)
Defines a relationship
Between several (independent) class types
Vehicle
LandBased WaterBased
Automobile MotorBoat
AutoBoat
Example:
Multiple Parents
Common Ancestor
Virtual Inheritance
The derived class AutoBoat…
Inherits Attributes and Properties
From
Automobile
MotorBoat
Vehicle
Vehicle
LandBased WaterBased
Automobile MotorBoat
AutoBoat
Derivation Hierarchy
• The class Vehicle is an abstraction…
– It represents an encapsulation of common
• Properties
• Attributes
• Its sole purpose
– Define a class from which to derive other classes….
• It encapsulates common
– Data members
– Function members
• Called
– Abstract Base Class
– Abstract Super Class
Class Derivation
Any class can serve as a base class…
– Thus a derived class can also be a base class
– Worth spending time at the outset of a design to develop
sound definitions
syntax
class DerivedClassName:specification BaseClassName
DerivedClassName - the class being derived
specification - specifies access to the base class
members
public
protected
private
- private by default
Class Derivation
Class C be derived from base class A - PUBLIC
class C : public A
In class C
The inherited public members of A
Appear as public members of C
If myValue is a public data member of A
myValue can be accessed publicly through instances of C
C myC;
myC.myValue; // ok
Class Derivation
Class C be derived from base class B - PRIVATE
class C : private B
In class C
The inherited public members of B
Appear as private members of C
if myValue is a public data member of B
myValue cannot be accessed publicly and directly through
instances of C
C myC;
myC.myValue; // compile error
Function members of C can still access public members of B as
public
Simple Inheritance - Example
#include <iostream>
class BaseClass {
public:
BaseClass( ) : baseValue (20) { };
BaseClass(int aValue) : baseValue (aValue) { };
int baseValue;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : derivedValue (10){ };
DerivedClass(int aDerivedValue) : BaseClass(15), derivedValue(aDerivedValue){ };
int getDerivedValue() { return derivedValue; }
private:
int derivedValue;
};
int main( )
{
BaseClass base;
DerivedClass child(5);
cout << base.baseValue << endl; // will print 20
cout << child.baseValue << endl; // will print 15
cout << child.getDerivedValue() << endl; // will print 5
return 0;
}
Derived Class – Public Inheritance
• Generally all data is private, so we just add additional data
members in the derived class by specifying them in the private
section
• Any base class member functions that are not specified in the
derived class are inherited unchanged, with the following
exceptions: constructor, destructor, copy constructor, and
operator=.
• Any base class member function that is declared in the derived
class’ private section is disabled in the derived class
• Any base class member function that is declared in the derived
class’ public section requires an overriding definition that will be
applied to objects of the derived class
• Additional member functions can be added in the derived class
Derived Class-Public Inheritance
class Derived : public Base {
// Any members that are not listed are inherited unchanged except
// for constructor, destructor, copy constructor, and operator=
public:
// Constructors, and destructors if defaults are not good
// Base members whose definitions are to change in Derived
// Additional public member functions
private:
// Additional data members (generally private)
// Additional private member functions
// Base members that should be disabled in Derived
};
Visibility rules
• Any private members in the base class are not accessible to the
derived class (because any member that is declared with private
visibility is accessible only to methods of the class)
• What if we want the derived class to have access to the base class
members?
1) use public access =>public access allows access to other classes in
addition to derived classes
2) use a friend declaration=>this is also poor design and would require friend
declaration for each derived class
3) make members protected =>allows access only to derived classes
A protected class member is private to every class except a derived class,
but declaring data members as protected or public violates the spirit of
encapsulation
1) write accessor and modifier methods =>the best alternative
Note: However, if a protected declaration allows you to avoid convoluted
code, then it is not unreasonable to use it.
Class Derivation
Constructors and Destructors
• Constructors and destructors are not inherited
– Each derived class should define its constructors/destructor
– If no constructor is written=> hidden constructor is generated and will call the
base default constructor for the inherited portion and then apply the default
initialization for any additional data members
• When a derived object is instantiated, memory is allocated for
– Base object
– Added parts
• Initialization occurs in two stages:
– the base class constructors are invoked to initialize the base objects
– the derived class constructor is used to complete the task
• The derived class constructor specifies appropriate base class
constructor in the initialization list
– If there is no constructor in base class, the compiler created default
constructor used
• If the base class is derived, the procedure is applied recursively
Inherited Member Initialization
• Initialized in two ways:
– If the base class has only a default constructor=> initialize the member
values in the body of the derived class constructor
– If the base class has a constructor with arguments=> the initialization list is
used to pass arguments to the base class constructors
syntax (for Single Base Class)
DerivedClass ( derivedClass args ) : BaseClass ( baseClass args )
{
DerivedClass constructor body
}
• The set of derived class constructor arguments may contain
initialization values for the base class arguments
Derived class DateTime
class DateTime : public Date // derived from base class Date
{
private:
// additional data members
int hour, minutes;
public:
// additional member functions
void DateTime(); //default constructor
void DateTime(const char* mm_dd_yy, int h, int mi); // constructor
void setTime(int h, int m);
void addMinutes(int m);
void addHours(int h);
void display(void) const; // overrides Date::display()
};
Derived Class DateTime
DateTime::DateTime(const char * mm_dd_yy, int h, int mi)
: Date(mm_dd_yy) , hours(h) , minutes(mi)
// invokes the constructor Date(const char* mmddyy) {}
void DateTime::display() const {
//add the code for displaying the date and time .
//Hint : cout<<(Date&)(*this)<<endl; will display the date
}
void DateTime::AddHours(int h) {
//make sure that if the hours goes more than 24 you have to add 1 day
// and you can do that as follows (*this) += 1;
}
Derived Class DateTime
int main(){
DateTime dt(”11/06/01”,20,15); //constructor
dt+=5; // operator+=() of class Date
cout << ”Date is: ” << justdt<<endl;
dt.AddHours(2); // AddHours() of class DateTime
dt.display(); // display() of class DateTime
return 0;
}

More Related Content

What's hot

Oop inheritance
Oop inheritanceOop inheritance
Oop inheritance
Zubair CH
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
Arslan Waseem
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
Inheritance
InheritanceInheritance
Inheritance
prabhat kumar
 
Inheritance
InheritanceInheritance
InheritanceTech_MX
 
Inheritance chapter-6-computer-science-with-c++ opt
Inheritance chapter-6-computer-science-with-c++ optInheritance chapter-6-computer-science-with-c++ opt
Inheritance chapter-6-computer-science-with-c++ opt
deepakskb2013
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vineeta Garg
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
Hirra Sultan
 
Ganesh groups
Ganesh groupsGanesh groups
Ganesh groups
Ganesh Amirineni
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
Muraleedhar Sundararajan
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiersSrinivas Reddy
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
sushamaGavarskar1
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Abhishek Khune
 
OCA JAVA - 1 Packages and Class Structure
 OCA JAVA - 1 Packages and Class Structure OCA JAVA - 1 Packages and Class Structure
OCA JAVA - 1 Packages and Class Structure
Fernando Gil
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
Arati Gadgil
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
MD SALEEM QAISAR
 

What's hot (19)

Inheritance
InheritanceInheritance
Inheritance
 
Oop inheritance
Oop inheritanceOop inheritance
Oop inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance chapter-6-computer-science-with-c++ opt
Inheritance chapter-6-computer-science-with-c++ optInheritance chapter-6-computer-science-with-c++ opt
Inheritance chapter-6-computer-science-with-c++ opt
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
Ganesh groups
Ganesh groupsGanesh groups
Ganesh groups
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiers
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
 
OCA JAVA - 1 Packages and Class Structure
 OCA JAVA - 1 Packages and Class Structure OCA JAVA - 1 Packages and Class Structure
OCA JAVA - 1 Packages and Class Structure
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
 

Similar to OOP

C++ presentation
C++ presentationC++ presentation
C++ presentation
SudhanshuVijay3
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
RAJ KUMAR
 
11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
LadallaRajKumar
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
AteeqaKokab1
 
session 24_Inheritance.ppt
session 24_Inheritance.pptsession 24_Inheritance.ppt
session 24_Inheritance.ppt
NAVANEETCHATURVEDI2
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
WaqarRaj1
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
SURBHI SAROHA
 
Inheritance
InheritanceInheritance
Inheritance
Pranali Chaudhari
 
Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03
sivakumarmcs
 
week14 (1).ppt
week14 (1).pptweek14 (1).ppt
week14 (1).ppt
amal68766
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
JP2B1197685ARamSaiPM
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
VishnuSupa
 
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdf
AneesAbbasi14
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
Muhammad Hammad Waseem
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
SadiqullahGhani1
 
29csharp
29csharp29csharp
29csharp
Sireesh K
 
29c
29c29c
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 

Similar to OOP (20)

C++ presentation
C++ presentationC++ presentation
C++ presentation
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
 
session 24_Inheritance.ppt
session 24_Inheritance.pptsession 24_Inheritance.ppt
session 24_Inheritance.ppt
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
 
OOPs & C++ UNIT 3
OOPs & C++ UNIT 3OOPs & C++ UNIT 3
OOPs & C++ UNIT 3
 
Inheritance
InheritanceInheritance
Inheritance
 
Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03
 
week14 (1).ppt
week14 (1).pptweek14 (1).ppt
week14 (1).ppt
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdf
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
29csharp
29csharp29csharp
29csharp
 
29c
29c29c
29c
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 

More from karan saini

Topology ppt
Topology pptTopology ppt
Topology ppt
karan saini
 
Tibor
TiborTibor
Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01
karan saini
 
Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)
karan saini
 
Snrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofskySnrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofsky
karan saini
 
Science
ScienceScience
Science
karan saini
 
Risc and cisc eugene clewlow
Risc and cisc   eugene clewlowRisc and cisc   eugene clewlow
Risc and cisc eugene clewlow
karan saini
 
Py4inf 05-iterations
Py4inf 05-iterationsPy4inf 05-iterations
Py4inf 05-iterations
karan saini
 
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)Py4inf 05-iterations (1)
Py4inf 05-iterations (1)
karan saini
 
Periodic table1
Periodic table1Periodic table1
Periodic table1
karan saini
 
Maths project
Maths projectMaths project
Maths project
karan saini
 
Lecturespecial
LecturespecialLecturespecial
Lecturespecial
karan saini
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
karan saini
 
Lcd monitors
Lcd monitorsLcd monitors
Lcd monitors
karan saini
 
Lab3
Lab3Lab3
L11cs2110sp13
L11cs2110sp13L11cs2110sp13
L11cs2110sp13
karan saini
 
Helen keller-1226880485154369-8
Helen keller-1226880485154369-8Helen keller-1226880485154369-8
Helen keller-1226880485154369-8
karan saini
 
Hardware
HardwareHardware
Hardware
karan saini
 
Gsm cdma1
Gsm cdma1Gsm cdma1
Gsm cdma1
karan saini
 
Final 121114041321-phpapp01
Final 121114041321-phpapp01Final 121114041321-phpapp01
Final 121114041321-phpapp01
karan saini
 

More from karan saini (20)

Topology ppt
Topology pptTopology ppt
Topology ppt
 
Tibor
TiborTibor
Tibor
 
Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01Thestoryofmylife 140221061604-phpapp01
Thestoryofmylife 140221061604-phpapp01
 
Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)Thestoryofmylife 140221061604-phpapp01 (1)
Thestoryofmylife 140221061604-phpapp01 (1)
 
Snrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofskySnrg2011 6.15.2.sta canney_suranofsky
Snrg2011 6.15.2.sta canney_suranofsky
 
Science
ScienceScience
Science
 
Risc and cisc eugene clewlow
Risc and cisc   eugene clewlowRisc and cisc   eugene clewlow
Risc and cisc eugene clewlow
 
Py4inf 05-iterations
Py4inf 05-iterationsPy4inf 05-iterations
Py4inf 05-iterations
 
Py4inf 05-iterations (1)
Py4inf 05-iterations (1)Py4inf 05-iterations (1)
Py4inf 05-iterations (1)
 
Periodic table1
Periodic table1Periodic table1
Periodic table1
 
Maths project
Maths projectMaths project
Maths project
 
Lecturespecial
LecturespecialLecturespecial
Lecturespecial
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Lcd monitors
Lcd monitorsLcd monitors
Lcd monitors
 
Lab3
Lab3Lab3
Lab3
 
L11cs2110sp13
L11cs2110sp13L11cs2110sp13
L11cs2110sp13
 
Helen keller-1226880485154369-8
Helen keller-1226880485154369-8Helen keller-1226880485154369-8
Helen keller-1226880485154369-8
 
Hardware
HardwareHardware
Hardware
 
Gsm cdma1
Gsm cdma1Gsm cdma1
Gsm cdma1
 
Final 121114041321-phpapp01
Final 121114041321-phpapp01Final 121114041321-phpapp01
Final 121114041321-phpapp01
 

Recently uploaded

Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
NaapbooksPrivateLimi
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 

Recently uploaded (20)

Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Visitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.appVisitor Management System in India- Vizman.app
Visitor Management System in India- Vizman.app
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 

OOP

  • 1. Inheritance In C++  Inheritance is a mechanism for • building class types from other class types • defining new class types to be a –specialization –augmentation of existing types
  • 2. Inheritance Subgroupings with respect to a parent are called – Subclass – Derived Class – Children The derived class – inherits from the parent all • characteristics • properties • capabilities – can modify or extend inherited abilities
  • 3. Inheritance VEHICLE LANDBASED AUTOMOBILE BICYCLE • Consider the vehicle hierarchy: • Note that each entity is also a class • Classes are used in an object centered paradigm as a means of encapsulating common data and functions shared by members of the class
  • 4. Class and Instance Hierarchy We actually have two hierarchies AUTOMOBILE BICYCLE LANDBASED VEHICLE myAutomyBicycle myLandBased myVehicle
  • 5. Single/Multiple Inheritance Single Inheritance Each class or instance object has a single parent Multiple Inheritance Classes inherit from multiple base classes ( might not have same ancestors as shown in the example below) Defines a relationship Between several (independent) class types Vehicle LandBased WaterBased Automobile MotorBoat AutoBoat Example: Multiple Parents Common Ancestor
  • 6. Virtual Inheritance The derived class AutoBoat… Inherits Attributes and Properties From Automobile MotorBoat Vehicle Vehicle LandBased WaterBased Automobile MotorBoat AutoBoat
  • 7. Derivation Hierarchy • The class Vehicle is an abstraction… – It represents an encapsulation of common • Properties • Attributes • Its sole purpose – Define a class from which to derive other classes…. • It encapsulates common – Data members – Function members • Called – Abstract Base Class – Abstract Super Class
  • 8. Class Derivation Any class can serve as a base class… – Thus a derived class can also be a base class – Worth spending time at the outset of a design to develop sound definitions syntax class DerivedClassName:specification BaseClassName DerivedClassName - the class being derived specification - specifies access to the base class members public protected private - private by default
  • 9. Class Derivation Class C be derived from base class A - PUBLIC class C : public A In class C The inherited public members of A Appear as public members of C If myValue is a public data member of A myValue can be accessed publicly through instances of C C myC; myC.myValue; // ok
  • 10. Class Derivation Class C be derived from base class B - PRIVATE class C : private B In class C The inherited public members of B Appear as private members of C if myValue is a public data member of B myValue cannot be accessed publicly and directly through instances of C C myC; myC.myValue; // compile error Function members of C can still access public members of B as public
  • 11. Simple Inheritance - Example #include <iostream> class BaseClass { public: BaseClass( ) : baseValue (20) { }; BaseClass(int aValue) : baseValue (aValue) { }; int baseValue; }; class DerivedClass : public BaseClass { public: DerivedClass() : derivedValue (10){ }; DerivedClass(int aDerivedValue) : BaseClass(15), derivedValue(aDerivedValue){ }; int getDerivedValue() { return derivedValue; } private: int derivedValue; }; int main( ) { BaseClass base; DerivedClass child(5); cout << base.baseValue << endl; // will print 20 cout << child.baseValue << endl; // will print 15 cout << child.getDerivedValue() << endl; // will print 5 return 0; }
  • 12. Derived Class – Public Inheritance • Generally all data is private, so we just add additional data members in the derived class by specifying them in the private section • Any base class member functions that are not specified in the derived class are inherited unchanged, with the following exceptions: constructor, destructor, copy constructor, and operator=. • Any base class member function that is declared in the derived class’ private section is disabled in the derived class • Any base class member function that is declared in the derived class’ public section requires an overriding definition that will be applied to objects of the derived class • Additional member functions can be added in the derived class
  • 13. Derived Class-Public Inheritance class Derived : public Base { // Any members that are not listed are inherited unchanged except // for constructor, destructor, copy constructor, and operator= public: // Constructors, and destructors if defaults are not good // Base members whose definitions are to change in Derived // Additional public member functions private: // Additional data members (generally private) // Additional private member functions // Base members that should be disabled in Derived };
  • 14. Visibility rules • Any private members in the base class are not accessible to the derived class (because any member that is declared with private visibility is accessible only to methods of the class) • What if we want the derived class to have access to the base class members? 1) use public access =>public access allows access to other classes in addition to derived classes 2) use a friend declaration=>this is also poor design and would require friend declaration for each derived class 3) make members protected =>allows access only to derived classes A protected class member is private to every class except a derived class, but declaring data members as protected or public violates the spirit of encapsulation 1) write accessor and modifier methods =>the best alternative Note: However, if a protected declaration allows you to avoid convoluted code, then it is not unreasonable to use it.
  • 15. Class Derivation Constructors and Destructors • Constructors and destructors are not inherited – Each derived class should define its constructors/destructor – If no constructor is written=> hidden constructor is generated and will call the base default constructor for the inherited portion and then apply the default initialization for any additional data members • When a derived object is instantiated, memory is allocated for – Base object – Added parts • Initialization occurs in two stages: – the base class constructors are invoked to initialize the base objects – the derived class constructor is used to complete the task • The derived class constructor specifies appropriate base class constructor in the initialization list – If there is no constructor in base class, the compiler created default constructor used • If the base class is derived, the procedure is applied recursively
  • 16. Inherited Member Initialization • Initialized in two ways: – If the base class has only a default constructor=> initialize the member values in the body of the derived class constructor – If the base class has a constructor with arguments=> the initialization list is used to pass arguments to the base class constructors syntax (for Single Base Class) DerivedClass ( derivedClass args ) : BaseClass ( baseClass args ) { DerivedClass constructor body } • The set of derived class constructor arguments may contain initialization values for the base class arguments
  • 17. Derived class DateTime class DateTime : public Date // derived from base class Date { private: // additional data members int hour, minutes; public: // additional member functions void DateTime(); //default constructor void DateTime(const char* mm_dd_yy, int h, int mi); // constructor void setTime(int h, int m); void addMinutes(int m); void addHours(int h); void display(void) const; // overrides Date::display() };
  • 18. Derived Class DateTime DateTime::DateTime(const char * mm_dd_yy, int h, int mi) : Date(mm_dd_yy) , hours(h) , minutes(mi) // invokes the constructor Date(const char* mmddyy) {} void DateTime::display() const { //add the code for displaying the date and time . //Hint : cout<<(Date&)(*this)<<endl; will display the date } void DateTime::AddHours(int h) { //make sure that if the hours goes more than 24 you have to add 1 day // and you can do that as follows (*this) += 1; }
  • 19. Derived Class DateTime int main(){ DateTime dt(”11/06/01”,20,15); //constructor dt+=5; // operator+=() of class Date cout << ”Date is: ” << justdt<<endl; dt.AddHours(2); // AddHours() of class DateTime dt.display(); // display() of class DateTime return 0; }