SlideShare uma empresa Scribd logo
1 de 27
Inheritance
Michael Heron
Introduction
• Last week we discussed object orientation a little bit.
• Introducing one of the key principles of object orientation –
encapsulation.
• This week we will round off our discussion of object
orientation.
• Today we talk about the principle of inheritance.
• Tomorrow we’re going to discuss general object design.
Encapsulation Revisited
• One of the things that makes encapsulation a powerful tool is
that we have one distinct unit to represent a collection of data
and methods.
• We can leverage this representation in various ways.
• It is the foundation of several other object oriented principles.
• One of the things that extend from this system is the principle
of inheritance.
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 C++
• At its basic level, relatively simple.
• A single colon is used in place of the extends keyword.
• We also include public before the class name.
• We have no access to variables and methods defined as
private.
• This is where the visibility modifiers we discussed last week come
into play.
Inheritance in C++
class Car {
private:
float price;
public:
void set_price (float p);
float query_price();
};
This is the header file for our class – remember classes in C++ are spread over two
files. The header file defines the class structure, and includes none of the code.
Inheritance in C++
#include "car.h”
void Car::set_price (float p) {
price = p;
}
float Car::query_price() {
return price;
}
This is the cpp file for the class – it defines the code, but doesn’t define what the class
structure is. That’s left for the header file.
Inheritance in C++
class ExtendedCar : public Car {
private:
float mpg;
public:
void set_mpg (float f);
float query_mpg();
};
float ExtendedCar::query_mpg() {
return mpg;
}
void ExtendedCar::set_mpg (float f) {
mpg = f;
}
Constructors
• It is often useful for us to be able to setup an object with
some starting values to its attributes.
• We can do this using a constructor method.
• This is a special method called whenever an object is created.
• Constructor methods work the same way as other methods.
• They just have a slightly different format.
Constructors in Theory
• It is called automatically when an object is initialized.
• When we create an object from a class.
• Can be used for any purpose, but most often used for
initializing data fields.
• We can provide a range of constructor methods inside an
object to deal with all eventualities.
Constructors
• Constructors must have the same name as the class in which
they are defined.
• Constructors have no return type.
• They are not void, the return type is actually omitted.
• They are usually declared as public.
• A well designed object will often provide several constructors.
• This is perfectly valid, provided they all have unique method
signatures.
Constructors in C++
• These are declared in the same way as any method, in the
header file:
class Car {
private:
float price;
public:
Car();
void set_price (float p);
float query_price();
};
Constructors in C++
• Data fields in a C++ constructor are initialised like so:
Car::Car() :
price (200.0),
colour ("black") {
}
C++ Constructor Code
Note that the method here has no return type – this distinguishes it from other
kinds of methods in C++.
Constructors in C++
• Initialization lists may look like function calls.
• They’re not.
• The name of the entries in the list refer specifically to the name
of attributes only.
• You can make use of parameters passed to constructors in the
initialization lists also.
Car::Car(float p) :
price (p) {
}
Rules of Constructors
• If no constructors are defined by the developer, a default case
is provided.
• This is a zero parameter constructor with no attached
functionality.
• If any developer-defined constructor exists, the compiler will
not provide one.
• Even if the defined constructor has parameters.
• You should always provide a zero parameter constructor.
• We won’t talk about why – it’s just Good Practice.
Constructors
• The constructor method gets called whenever an object is
created.
• The compiler figures out which constructor should be called
by examining the parameter list.
• Only one of the constructors will be called.
• As far as C++ is concerned, they are all different methods even if
they share a name.
Default Parameters
• C++ Constructors (and methods) allow for default values to be
specified for parameters.
• This is a feature not available in Java.
• Default values are specified in the declaration only.
• Parameters with default values must come at the end of the
parameter list.
Declaring And Using A Default
Parameter
Declaration
Car (float, string = "bright green");
Using
int main() {
Car my_car (500.0);
cout << my_car.query_price() << endl;
return 1;
}
Why Use A Constructor?
• Constructors allow for the developer to ensure a minimum
level of data is contained within an object.
• Avoids the need to hard-code validation into data algorithms.
• You can assume that the objects you are working with will be
configured in some syntactically correct way.
Why Use A Constructor?
• In large multi-developer projects, while you can often assume
good faith, you cannot rely on it.
• You can provide documentation to say that every instantiation of
an object should be followed by calls to accessors. You can’t
ensure people follow it.
• Constructor methods allow you to enforce at compilation the
correctness of object configuration.
• The earlier in the development process errors are encountered,
the easier they are to fix.
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,
float mpg = 50.0);
void set_mpg (float f);
float query_mpg();
};
ExtendedCar::ExtendedCar (float cost, float mpg)
: Car(cost),
mpg (mpg) {
}
Summary
• Inheritance is a powerful tool for reusability in C++.
• We only touch on it in this module – no need to worry too much
about it.
• Constructor methods in a C++ program permit us to have
control over the starting values of data fields in our objects.
• Important and useful.

Mais conteúdo relacionado

Mais procurados

Object Oriented Programming with COBOL
Object Oriented Programming with COBOLObject Oriented Programming with COBOL
Object Oriented Programming with COBOLMicro Focus
 
XKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & ConstructsXKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & ConstructsNicolas Demengel
 
C++ unit-1-part-9
C++ unit-1-part-9C++ unit-1-part-9
C++ unit-1-part-9Jadavsejal
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending ClassesNilesh Dalvi
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building BlocksCate Huston
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
C++ unit-2-part-3
C++ unit-2-part-3C++ unit-2-part-3
C++ unit-2-part-3Jadavsejal
 
C++ unit-2-part-1
C++ unit-2-part-1C++ unit-2-part-1
C++ unit-2-part-1Jadavsejal
 
Maths&programming forartists wip
Maths&programming forartists wipMaths&programming forartists wip
Maths&programming forartists wipkedar nath
 
C++ unit-1-part-13
C++ unit-1-part-13C++ unit-1-part-13
C++ unit-1-part-13Jadavsejal
 

Mais procurados (13)

Inheritance
InheritanceInheritance
Inheritance
 
Object Oriented Programming with COBOL
Object Oriented Programming with COBOLObject Oriented Programming with COBOL
Object Oriented Programming with COBOL
 
XKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & ConstructsXKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & Constructs
 
C++ unit-1-part-9
C++ unit-1-part-9C++ unit-1-part-9
C++ unit-1-part-9
 
Inheritance : Extending Classes
Inheritance : Extending ClassesInheritance : Extending Classes
Inheritance : Extending Classes
 
Java Building Blocks
Java Building BlocksJava Building Blocks
Java Building Blocks
 
From DOT to Dotty
From DOT to DottyFrom DOT to Dotty
From DOT to Dotty
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 
class and objects
class and objectsclass and objects
class and objects
 
C++ unit-2-part-3
C++ unit-2-part-3C++ unit-2-part-3
C++ unit-2-part-3
 
C++ unit-2-part-1
C++ unit-2-part-1C++ unit-2-part-1
C++ unit-2-part-1
 
Maths&programming forartists wip
Maths&programming forartists wipMaths&programming forartists wip
Maths&programming forartists wip
 
C++ unit-1-part-13
C++ unit-1-part-13C++ unit-1-part-13
C++ unit-1-part-13
 

Destaque

PATTERNS01 - An Introduction to Design Patterns
PATTERNS01 - An Introduction to Design PatternsPATTERNS01 - An Introduction to Design Patterns
PATTERNS01 - An Introduction to Design PatternsMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael 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
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
PATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design PatternPATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design PatternMichael Heron
 
Questpond - Top 10 Interview Questions and Answers on OOPS
Questpond - Top 10 Interview Questions and Answers on OOPSQuestpond - Top 10 Interview Questions and Answers on OOPS
Questpond - Top 10 Interview Questions and Answers on OOPSgdrealspace
 
How I Learned To Apply Design Patterns
How I Learned To Apply Design PatternsHow I Learned To Apply Design Patterns
How I Learned To Apply Design PatternsAndy Maleh
 
C# OOP Advanced Concepts
C# OOP Advanced ConceptsC# OOP Advanced Concepts
C# OOP Advanced Conceptsagni_agbc
 
Software Design Patterns - Selecting the right design pattern
Software Design Patterns - Selecting the right design patternSoftware Design Patterns - Selecting the right design pattern
Software Design Patterns - Selecting the right design patternJoao Pereira
 

Destaque (11)

PATTERNS01 - An Introduction to Design Patterns
PATTERNS01 - An Introduction to Design PatternsPATTERNS01 - An Introduction to Design Patterns
PATTERNS01 - An Introduction to Design Patterns
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
PATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design PatternPATTERNS05 - Guidelines for Choosing a Design Pattern
PATTERNS05 - Guidelines for Choosing a Design Pattern
 
Questpond - Top 10 Interview Questions and Answers on OOPS
Questpond - Top 10 Interview Questions and Answers on OOPSQuestpond - Top 10 Interview Questions and Answers on OOPS
Questpond - Top 10 Interview Questions and Answers on OOPS
 
How I Learned To Apply Design Patterns
How I Learned To Apply Design PatternsHow I Learned To Apply Design Patterns
How I Learned To Apply Design Patterns
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
C# OOP Advanced Concepts
C# OOP Advanced ConceptsC# OOP Advanced Concepts
C# OOP Advanced Concepts
 
Software Design Patterns - Selecting the right design pattern
Software Design Patterns - Selecting the right design patternSoftware Design Patterns - Selecting the right design pattern
Software Design Patterns - Selecting the right design pattern
 

Semelhante a CPP15 - Inheritance

[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its TypesMuhammad Hammad Waseem
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)Vu Tran Lam
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers2CPP06 - Arrays and Pointers
2CPP06 - Arrays and PointersMichael Heron
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming LanguageSteve Johnson
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++KAUSHAL KUMAR JHA
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application DevelopmentDhaval Kaneria
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4Ali Aminian
 
Programming Terminology
Programming TerminologyProgramming Terminology
Programming TerminologyMichael Henson
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective cSunny Shaikh
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1stConnex
 
2classes in c#
2classes in c#2classes in c#
2classes in c#Sireesh K
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsakreyi
 
2CPP07 - Inheritance
2CPP07 - Inheritance2CPP07 - Inheritance
2CPP07 - InheritanceMichael Heron
 
C++ Introduction brown bag
C++ Introduction brown bagC++ Introduction brown bag
C++ Introduction brown bagJacob Green
 

Semelhante a CPP15 - Inheritance (20)

Introduction to c ++ part -1
Introduction to c ++   part -1Introduction to c ++   part -1
Introduction to c ++ part -1
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
Intro To C++ - Class #19: Functions
Intro To C++ - Class #19: FunctionsIntro To C++ - Class #19: Functions
Intro To C++ - Class #19: Functions
 
Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)Session 3 - Object oriented programming with Objective-C (part 1)
Session 3 - Object oriented programming with Objective-C (part 1)
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers2CPP06 - Arrays and Pointers
2CPP06 - Arrays and Pointers
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++
 
Objective-C for iOS Application Development
Objective-C for iOS Application DevelopmentObjective-C for iOS Application Development
Objective-C for iOS Application Development
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
Programming Terminology
Programming TerminologyProgramming Terminology
Programming Terminology
 
Introduction to objective c
Introduction to objective cIntroduction to objective c
Introduction to objective c
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
2classes in c#
2classes in c#2classes in c#
2classes in c#
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
2CPP07 - Inheritance
2CPP07 - Inheritance2CPP07 - Inheritance
2CPP07 - Inheritance
 
Java
JavaJava
Java
 
C++ Introduction brown bag
C++ Introduction brown bagC++ Introduction brown bag
C++ Introduction brown bag
 

Mais 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
 
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
 
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
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator OverloadingMichael Heron
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method OverridingMichael Heron
 

Mais 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
 
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
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
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
 
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
 
2CPP13 - Operator Overloading
2CPP13 - Operator Overloading2CPP13 - Operator Overloading
2CPP13 - Operator Overloading
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method Overriding
 

Último

Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 

Último (20)

Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 

CPP15 - Inheritance

  • 2. Introduction • Last week we discussed object orientation a little bit. • Introducing one of the key principles of object orientation – encapsulation. • This week we will round off our discussion of object orientation. • Today we talk about the principle of inheritance. • Tomorrow we’re going to discuss general object design.
  • 3. Encapsulation Revisited • One of the things that makes encapsulation a powerful tool is that we have one distinct unit to represent a collection of data and methods. • We can leverage this representation in various ways. • It is the foundation of several other object oriented principles. • One of the things that extend from this system is the principle of inheritance.
  • 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 C++ • At its basic level, relatively simple. • A single colon is used in place of the extends keyword. • We also include public before the class name. • We have no access to variables and methods defined as private. • This is where the visibility modifiers we discussed last week come into play.
  • 9. Inheritance in C++ class Car { private: float price; public: void set_price (float p); float query_price(); }; This is the header file for our class – remember classes in C++ are spread over two files. The header file defines the class structure, and includes none of the code.
  • 10. Inheritance in C++ #include "car.h” void Car::set_price (float p) { price = p; } float Car::query_price() { return price; } This is the cpp file for the class – it defines the code, but doesn’t define what the class structure is. That’s left for the header file.
  • 11. Inheritance in C++ class ExtendedCar : public Car { private: float mpg; public: void set_mpg (float f); float query_mpg(); }; float ExtendedCar::query_mpg() { return mpg; } void ExtendedCar::set_mpg (float f) { mpg = f; }
  • 12. Constructors • It is often useful for us to be able to setup an object with some starting values to its attributes. • We can do this using a constructor method. • This is a special method called whenever an object is created. • Constructor methods work the same way as other methods. • They just have a slightly different format.
  • 13. Constructors in Theory • It is called automatically when an object is initialized. • When we create an object from a class. • Can be used for any purpose, but most often used for initializing data fields. • We can provide a range of constructor methods inside an object to deal with all eventualities.
  • 14. Constructors • Constructors must have the same name as the class in which they are defined. • Constructors have no return type. • They are not void, the return type is actually omitted. • They are usually declared as public. • A well designed object will often provide several constructors. • This is perfectly valid, provided they all have unique method signatures.
  • 15. Constructors in C++ • These are declared in the same way as any method, in the header file: class Car { private: float price; public: Car(); void set_price (float p); float query_price(); };
  • 16. Constructors in C++ • Data fields in a C++ constructor are initialised like so: Car::Car() : price (200.0), colour ("black") { } C++ Constructor Code Note that the method here has no return type – this distinguishes it from other kinds of methods in C++.
  • 17. Constructors in C++ • Initialization lists may look like function calls. • They’re not. • The name of the entries in the list refer specifically to the name of attributes only. • You can make use of parameters passed to constructors in the initialization lists also. Car::Car(float p) : price (p) { }
  • 18. Rules of Constructors • If no constructors are defined by the developer, a default case is provided. • This is a zero parameter constructor with no attached functionality. • If any developer-defined constructor exists, the compiler will not provide one. • Even if the defined constructor has parameters. • You should always provide a zero parameter constructor. • We won’t talk about why – it’s just Good Practice.
  • 19. Constructors • The constructor method gets called whenever an object is created. • The compiler figures out which constructor should be called by examining the parameter list. • Only one of the constructors will be called. • As far as C++ is concerned, they are all different methods even if they share a name.
  • 20. Default Parameters • C++ Constructors (and methods) allow for default values to be specified for parameters. • This is a feature not available in Java. • Default values are specified in the declaration only. • Parameters with default values must come at the end of the parameter list.
  • 21. Declaring And Using A Default Parameter Declaration Car (float, string = "bright green"); Using int main() { Car my_car (500.0); cout << my_car.query_price() << endl; return 1; }
  • 22. Why Use A Constructor? • Constructors allow for the developer to ensure a minimum level of data is contained within an object. • Avoids the need to hard-code validation into data algorithms. • You can assume that the objects you are working with will be configured in some syntactically correct way.
  • 23. Why Use A Constructor? • In large multi-developer projects, while you can often assume good faith, you cannot rely on it. • You can provide documentation to say that every instantiation of an object should be followed by calls to accessors. You can’t ensure people follow it. • Constructor methods allow you to enforce at compilation the correctness of object configuration. • The earlier in the development process errors are encountered, the easier they are to fix.
  • 24. 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.
  • 25. 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.
  • 26. Constructors in C++ class ExtendedCar : public Car { private: float mpg; public: ExtendedCar( float cost = 100.0, float mpg = 50.0); void set_mpg (float f); float query_mpg(); }; ExtendedCar::ExtendedCar (float cost, float mpg) : Car(cost), mpg (mpg) { }
  • 27. Summary • Inheritance is a powerful tool for reusability in C++. • We only touch on it in this module – no need to worry too much about it. • Constructor methods in a C++ program permit us to have control over the starting values of data fields in our objects. • Important and useful.