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
 
From DOT to Dotty
From DOT to DottyFrom DOT to Dotty
From DOT to DottyMartin Odersky
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphismGanesh Hogade
 
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
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - InheritanceMichael 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
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - ShadingMichael 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
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - ModifiersMichael Heron
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IOMichael Heron
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - TemplatesMichael 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

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
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
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
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
 
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
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfWilly Marroquin (WillyDevNET)
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 

Último (20)

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
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
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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...
 
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
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 

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.