SlideShare a Scribd company logo
INHERITANCE
Michael Heron
Introduction
• There are three pillars fundamental to the edifice that is
object oriented programming.
• Inheritance
• Encapsulation
• Polymorphism
• It is these three things that turn object orientation from a
gimmick into an extremely powerful programming tool.
Inheritance
• In this lecture we are going to talk about inheritance and
how it can be applied to C++ programs.
• There are several important differences here between Java and
C++.
• Java and C# are single inheritance languages.
• C++ supports multiple inheritance.
• This is much more powerful, but also very difficult to do well.
Inheritance
• The concept of inheritance is borrowed from the natural
world.
• You get traits from your parents and you pass them on to your
offspring.
• In C++, any class can be the parent of any other object.
• The child class gains all of the methods and attributes of the
parent.
• This can be modified, more on that later.
Inheritance in the Natural World
Inheritance
• Inheritance is a powerful concept for several reasons.
• Ensures consistency of code across multiple different objects.
• Allows for code to be collated in one location with the concomitant
impact on maintainability.
• Changes in the code rattle through all objects making use of it.
• Supports for code re-use.
• Theoretically…
Inheritance
• In C++, the most general case of a code system belongs
at the top of the inheritance hierarchy.
• It is successively specialised into new and more precise
implementations.
• Children specialise their parents
• Parents generalise their children.
• Functionality and attributes belong to the most general
class in which they are cohesive.
Inheritance
• In Java, the concept is simple.
• You create an inheritance relationship by having one class extend
another.
• The newly extended class gains all of the attributes and
methods of the parent.
• It can be used, wholesale, in place of the parent if needed.
• We can also add and specialise attributes and
behaviours.
• This is the important feature of inheritance.
Inheritance in Java
public class BankAccount {
private int balance;
public void setBalance (int b) {
balance=b;
}
public int getBalance() {
return balance;
}
}
public class MainClass {
public static void main (String args[]) {
BankAccount myAccount;
myAccount = new BankAccount();
myAccount.setBalance (100);
System.out.println ("Balance is: " + myAccount.getBalance());
}
}
Inheritance in Java
public class ExtendedBankAccount extends BankAccount{
private int overdraft;
public boolean adjustBalance (int val) {
if (getBalance() - val < 0 - overdraft) {
return false;
}
setBalance (getBalance() - val);
return true;
}
}
Constructors And Inheritance
• When a specialised class is instantiated, it calls the
constructor on the specialised class.
• If it doesn’t find a valid one it will error, even if one exists in the
parent.
• Constructors can propagate invocations up the object
hierarchy through the use of the super keyword.
• super always refers to the parent object in Java.
• Easy to do, because each child has only one parent.
• In a constructor, must always be the first method call.
• Everywhere else, it can be anywhere.
Constructors and Inheritance
public class BankAccount {
private int balance;
public BankAccount() {
balance = 0;
}
public BankAccount (int
startBalance) {
setBalance (startBalance);
}
public void setBalance (int b) {
balance=b;
}
public int getBalance() {
return balance;
}
}
public class ExtendedBankAccount extends
BankAccount{
private int overdraft;
public ExtendedBankAccount (int startBalance) {
super (startBalance);
}
public ExtendedBankAccount (int startBalance, int
startOverdraft) {
super (startBalance);
overdraft = startOverdraft;
}
public boolean adjustBalance (int val) {
if (getBalance() - val < 0 - overdraft) {
return false;
}
setBalance (getBalance() - val);
return true;
}
}
Inheritance in C++
• At its basic level, very similar to Java.
• A single colon is used in place of the extends keyword.
• We also include public before the class name.
• We’ll talk about why later.
• We have no access to variables and methods defined as
private.
• More on that in the next lecture.
Inheritance in C++
class ExtendedCar : public Car {
private:
float mpg;
public:
ExtendedCar(float mpg = 50.0);
void set_mpg (float f);
float query_mpg();
};
ExtendedCar::ExtendedCar (float mpg) :
mpg (mpg) {
}
float ExtendedCar::query_mpg() {
return mpg;
}
void ExtendedCar::set_mpg (float f) {
mpg = f;
}
Constructors in C++
• Constructors in specialised C++ classes work in a slightly
different way to in Java.
• Constructors cannot set the value in parent classes.
• This syntactically forbidden in C++.
• By default, the matching constructor in the derived class (child class)
will be called.
• Then the default construtor in the parent will be called.
• From our earlier example, the code will call the matching
constructor in ExtendedCar, and then the parameterless
constructor in Car.
Constructors in C++
• If we want to change that behaviour, we must indicate so
to the constructor.
• In our implementation for the constructor, we indicate which of the
constructors in the parent class are to be executed.
• We must handle the provision of the values ourselves.
Constructors in C++
class ExtendedCar : public Car {
private:
float mpg;
public:
ExtendedCar(
float cost = 100.0,
string colour = "black",
int max_size = 10, float mpg = 50.0);
void set_mpg (float f);
float query_mpg();
};
ExtendedCar::ExtendedCar (float cost, string colour, int max_size, float mpg)
: Car(cost, colour, max_size),
mpg (mpg) {
}
Multiple Inheritance
• The biggest distinction between C++ and Java inheritance
models is that C++ permits multiple inheritance.
• Java and C# do not provide this.
• It must be used extremely carefully.
• If you are unsure what you are doing, it is tremendously easy to make
a huge mess of a program.
• It is in fact something best avoided.
• Usually.
Multiple Inheritance
• We will touch on syntax, rather than discuss it.
• Don’t want to introduce something I don’t want you using!
• However, important you understand what is happening when you
see it.
• Inheritance defined in the same way as with a single
class.
• Separate classes to be inherited with a comma
• Class SuperVehicle: public Car, public Plane
Multiple Inheritance
• What are the problems with multiple inheritance?
• Hugely increased program complexity
• Problems with ambigious function calls.
• The Diamond Problem
• Hardly ever really needed.
• For simple applications, interfaces suffice.
• For more complicated situations, design patterns exist to resolve all the
requirements.
• Some languages permit multiple inheritance but resolve some
of the technical issues.
• C++ isn’t one of them.
Summary
• Inheritance is an extremely powerful tool.
• Provides opportunities for code re-use and maintainability.
• Inheritance in C++ is very similar to inheritance in Java.
• With some exceptions.
• C++ permits multiple inheritance.
• Not something you often need.

More Related Content

What's hot

Inheritance
InheritanceInheritance
Inheritance
Jancirani Selvam
 
CPP15 - Inheritance
CPP15 - InheritanceCPP15 - Inheritance
CPP15 - Inheritance
Michael Heron
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)
farhan amjad
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Inheritance in c++ by Manan Pasricha
Inheritance in c++ by Manan PasrichaInheritance in c++ by Manan Pasricha
Inheritance in c++ by Manan Pasricha
MananPasricha
 
Inheritance and Interfaces
Inheritance and InterfacesInheritance and Interfaces
Inheritance and Interfaces
NAGASURESH MANOHARAN
 
Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++
Sujan Mia
 
Shivani Chouhan ,BCA ,2nd Year
Shivani Chouhan ,BCA ,2nd YearShivani Chouhan ,BCA ,2nd Year
Shivani Chouhan ,BCA ,2nd Year
dezyneecole
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 

What's hot (9)

Inheritance
InheritanceInheritance
Inheritance
 
CPP15 - Inheritance
CPP15 - InheritanceCPP15 - Inheritance
CPP15 - Inheritance
 
Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)Inheritance, polymorphisam, abstract classes and composition)
Inheritance, polymorphisam, abstract classes and composition)
 
class and objects
class and objectsclass and objects
class and objects
 
Inheritance in c++ by Manan Pasricha
Inheritance in c++ by Manan PasrichaInheritance in c++ by Manan Pasricha
Inheritance in c++ by Manan Pasricha
 
Inheritance and Interfaces
Inheritance and InterfacesInheritance and Interfaces
Inheritance and Interfaces
 
Multiple inheritance in c++
Multiple inheritance in c++Multiple inheritance in c++
Multiple inheritance in c++
 
Shivani Chouhan ,BCA ,2nd Year
Shivani Chouhan ,BCA ,2nd YearShivani Chouhan ,BCA ,2nd Year
Shivani Chouhan ,BCA ,2nd Year
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 

Viewers also liked

Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritance
Shrija Madhu
 
inheritance in C++
inheritance in C++inheritance in C++
inheritance in C++
tayyaba nawaz
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Paumil Patel
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple Inheritance
adil raja
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
Arslan Waseem
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
daxesh chauhan
 
Inheritance
InheritanceInheritance
InheritanceTech_MX
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 

Viewers also liked (11)

Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritance
 
inheritance in C++
inheritance in C++inheritance in C++
inheritance in C++
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Multiple Inheritance
Multiple InheritanceMultiple Inheritance
Multiple Inheritance
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
 
Inheritance
InheritanceInheritance
Inheritance
 
C++ Inheritance
C++ InheritanceC++ Inheritance
C++ Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 

Similar to 2CPP07 - Inheritance

Java_notes.ppt
Java_notes.pptJava_notes.ppt
Java_notes.ppt
tuyambazejeanclaude
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS Concept
Richa Gupta
 
How would you implement multiple inheritance in java
How would you implement multiple inheritance in javaHow would you implement multiple inheritance in java
How would you implement multiple inheritance in javaTyagi2636
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
RahulAnanda1
 
Inheritance in OOPs with java
Inheritance in OOPs with javaInheritance in OOPs with java
Inheritance in OOPs with java
AAKANKSHA JAIN
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
Michael Heron
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++
KAUSHAL KUMAR JHA
 
Inheritance_abstractclass_interface.pdf
Inheritance_abstractclass_interface.pdfInheritance_abstractclass_interface.pdf
Inheritance_abstractclass_interface.pdf
kshitijsaini9
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
Hari Christian
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwords
Raja Sekhar
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
kristinatemen
 
29csharp
29csharp29csharp
29csharp
Sireesh K
 
29c
29c29c
Inheritance
InheritanceInheritance
Inheritance
Munsif Ullah
 
C++ vs Java: Which one is the best?
C++ vs Java: Which one is the best?C++ vs Java: Which one is the best?
C++ vs Java: Which one is the best?
calltutors
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Lovely Professional University
 
OOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdfOOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdf
Anant240318
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
AteeqaKokab1
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
SamuelAnsong6
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
PRIYACHAURASIYA25
 

Similar to 2CPP07 - Inheritance (20)

Java_notes.ppt
Java_notes.pptJava_notes.ppt
Java_notes.ppt
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS Concept
 
How would you implement multiple inheritance in java
How would you implement multiple inheritance in javaHow would you implement multiple inheritance in java
How would you implement multiple inheritance in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Inheritance in OOPs with java
Inheritance in OOPs with javaInheritance in OOPs with java
Inheritance in OOPs with java
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++
 
Inheritance_abstractclass_interface.pdf
Inheritance_abstractclass_interface.pdfInheritance_abstractclass_interface.pdf
Inheritance_abstractclass_interface.pdf
 
04 Java Language And OOP Part IV
04 Java Language And OOP Part IV04 Java Language And OOP Part IV
04 Java Language And OOP Part IV
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwords
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
 
29csharp
29csharp29csharp
29csharp
 
29c
29c29c
29c
 
Inheritance
InheritanceInheritance
Inheritance
 
C++ vs Java: Which one is the best?
C++ vs Java: Which one is the best?C++ vs Java: Which one is the best?
C++ vs Java: Which one is the best?
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
OOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdfOOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdf
 
INHERITANCE.pptx
INHERITANCE.pptxINHERITANCE.pptx
INHERITANCE.pptx
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 

More from Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
Michael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
Michael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
Michael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
Michael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
Michael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
Michael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
Michael Heron
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
Michael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
Michael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
Michael Heron
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
Michael Heron
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
Michael Heron
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
Michael Heron
 

More from Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 

Recently uploaded

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
 
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
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
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
 
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
 
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
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
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
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 

Recently uploaded (20)

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
 
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
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
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|...
 
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
 
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
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
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...
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 

2CPP07 - Inheritance

  • 2. Introduction • There are three pillars fundamental to the edifice that is object oriented programming. • Inheritance • Encapsulation • Polymorphism • It is these three things that turn object orientation from a gimmick into an extremely powerful programming tool.
  • 3. Inheritance • In this lecture we are going to talk about inheritance and how it can be applied to C++ programs. • There are several important differences here between Java and C++. • Java and C# are single inheritance languages. • C++ supports multiple inheritance. • This is much more powerful, but also very difficult to do well.
  • 4. Inheritance • The concept of inheritance is borrowed from the natural world. • You get traits from your parents and you pass them on to your offspring. • In C++, any class can be the parent of any other object. • The child class gains all of the methods and attributes of the parent. • This can be modified, more on that later.
  • 5. Inheritance in the Natural World
  • 6. Inheritance • Inheritance is a powerful concept for several reasons. • Ensures consistency of code across multiple different objects. • Allows for code to be collated in one location with the concomitant impact on maintainability. • Changes in the code rattle through all objects making use of it. • Supports for code re-use. • Theoretically…
  • 7. Inheritance • In C++, the most general case of a code system belongs at the top of the inheritance hierarchy. • It is successively specialised into new and more precise implementations. • Children specialise their parents • Parents generalise their children. • Functionality and attributes belong to the most general class in which they are cohesive.
  • 8. Inheritance • In Java, the concept is simple. • You create an inheritance relationship by having one class extend another. • The newly extended class gains all of the attributes and methods of the parent. • It can be used, wholesale, in place of the parent if needed. • We can also add and specialise attributes and behaviours. • This is the important feature of inheritance.
  • 9. Inheritance in Java public class BankAccount { private int balance; public void setBalance (int b) { balance=b; } public int getBalance() { return balance; } } public class MainClass { public static void main (String args[]) { BankAccount myAccount; myAccount = new BankAccount(); myAccount.setBalance (100); System.out.println ("Balance is: " + myAccount.getBalance()); } }
  • 10. Inheritance in Java public class ExtendedBankAccount extends BankAccount{ private int overdraft; public boolean adjustBalance (int val) { if (getBalance() - val < 0 - overdraft) { return false; } setBalance (getBalance() - val); return true; } }
  • 11. Constructors And Inheritance • When a specialised class is instantiated, it calls the constructor on the specialised class. • If it doesn’t find a valid one it will error, even if one exists in the parent. • Constructors can propagate invocations up the object hierarchy through the use of the super keyword. • super always refers to the parent object in Java. • Easy to do, because each child has only one parent. • In a constructor, must always be the first method call. • Everywhere else, it can be anywhere.
  • 12. Constructors and Inheritance public class BankAccount { private int balance; public BankAccount() { balance = 0; } public BankAccount (int startBalance) { setBalance (startBalance); } public void setBalance (int b) { balance=b; } public int getBalance() { return balance; } } public class ExtendedBankAccount extends BankAccount{ private int overdraft; public ExtendedBankAccount (int startBalance) { super (startBalance); } public ExtendedBankAccount (int startBalance, int startOverdraft) { super (startBalance); overdraft = startOverdraft; } public boolean adjustBalance (int val) { if (getBalance() - val < 0 - overdraft) { return false; } setBalance (getBalance() - val); return true; } }
  • 13. Inheritance in C++ • At its basic level, very similar to Java. • A single colon is used in place of the extends keyword. • We also include public before the class name. • We’ll talk about why later. • We have no access to variables and methods defined as private. • More on that in the next lecture.
  • 14. Inheritance in C++ class ExtendedCar : public Car { private: float mpg; public: ExtendedCar(float mpg = 50.0); void set_mpg (float f); float query_mpg(); }; ExtendedCar::ExtendedCar (float mpg) : mpg (mpg) { } float ExtendedCar::query_mpg() { return mpg; } void ExtendedCar::set_mpg (float f) { mpg = f; }
  • 15. Constructors in C++ • Constructors in specialised C++ classes work in a slightly different way to in Java. • Constructors cannot set the value in parent classes. • This syntactically forbidden in C++. • By default, the matching constructor in the derived class (child class) will be called. • Then the default construtor in the parent will be called. • From our earlier example, the code will call the matching constructor in ExtendedCar, and then the parameterless constructor in Car.
  • 16. Constructors in C++ • If we want to change that behaviour, we must indicate so to the constructor. • In our implementation for the constructor, we indicate which of the constructors in the parent class are to be executed. • We must handle the provision of the values ourselves.
  • 17. Constructors in C++ class ExtendedCar : public Car { private: float mpg; public: ExtendedCar( float cost = 100.0, string colour = "black", int max_size = 10, float mpg = 50.0); void set_mpg (float f); float query_mpg(); }; ExtendedCar::ExtendedCar (float cost, string colour, int max_size, float mpg) : Car(cost, colour, max_size), mpg (mpg) { }
  • 18. Multiple Inheritance • The biggest distinction between C++ and Java inheritance models is that C++ permits multiple inheritance. • Java and C# do not provide this. • It must be used extremely carefully. • If you are unsure what you are doing, it is tremendously easy to make a huge mess of a program. • It is in fact something best avoided. • Usually.
  • 19. Multiple Inheritance • We will touch on syntax, rather than discuss it. • Don’t want to introduce something I don’t want you using! • However, important you understand what is happening when you see it. • Inheritance defined in the same way as with a single class. • Separate classes to be inherited with a comma • Class SuperVehicle: public Car, public Plane
  • 20. Multiple Inheritance • What are the problems with multiple inheritance? • Hugely increased program complexity • Problems with ambigious function calls. • The Diamond Problem • Hardly ever really needed. • For simple applications, interfaces suffice. • For more complicated situations, design patterns exist to resolve all the requirements. • Some languages permit multiple inheritance but resolve some of the technical issues. • C++ isn’t one of them.
  • 21. Summary • Inheritance is an extremely powerful tool. • Provides opportunities for code re-use and maintainability. • Inheritance in C++ is very similar to inheritance in Java. • With some exceptions. • C++ permits multiple inheritance. • Not something you often need.