SlideShare une entreprise Scribd logo
1  sur  21
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.

Contenu connexe

Tendances

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 PasrichaMananPasricha
 
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 Yeardezyneecole
 
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
 

Tendances (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)
 

En vedette (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
 

Similaire à 2CPP07 - Inheritance

Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS ConceptRicha 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 javaRahulAnanda1
 
Inheritance in OOPs with java
Inheritance in OOPs with javaInheritance in OOPs with java
Inheritance in OOPs with javaAAKANKSHA JAIN
 
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.pdfkshitijsaini9
 
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 IVHari Christian
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsRaja Sekhar
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxkristinatemen
 
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
 
OOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdfOOP Assign No.03(AP).pdf
OOP Assign No.03(AP).pdfAnant240318
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionSamuelAnsong6
 

Similaire à 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
 
29c
29c29c
29c
 
29csharp
29csharp29csharp
29csharp
 
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
 

Plus de Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael 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 SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael 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 RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - AbstractionMichael Heron
 

Plus de 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
 

Dernier

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Dernier (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 

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.