SlideShare ist ein Scribd-Unternehmen logo
1 von 20
METHOD OVERRIDING
Michael Heron
Introduction
• In the last lecture we talked about method overloading.
• In this one we are going to talk about method overriding.
• The two are often confused, but are entirely different systems.
• One is based on the idea of unique identification of
methods.
• The other is based on being able to specialise behaviours
through inheritance.
Method Overriding
• When we override a method, we specialise it as the child
class as part of an inherited relationship.
• The usual rules of virtual functions apply here for C++.
• Usually what we do here is subtly alter the functionality
and then pass the results of our specialisation onto the
parent method.
Method Overriding
• The chain of invocation for a method in C++ depends on
its virtuality.
• If it is not virtual, the base method gets called always.
• If it is virtual, the most specialised implementation gets called.
• For virtual methods, we then have control over the chain
of invocation.
• We can decide how invocations filter up and down the chain.
The Chain of Invocation
• This is a fancy way of saying ‘which functions get
executed when’.
• A well over-ridden function will tend to pass function calls back onto
their parent classes.
• There is nothing to stop you entirely handling a function in
the most specialised instance.
• It’s generally not very good design.
• Violates the principles of encapsulation.
Employee (Base Class)
class Employee {
private:
int payscale;
public:
int query_payscale();
void set_payscale (int p);
virtual bool can_hire_and_fire();
virtual bool has_authority (string);
};
bool Employee::has_authority (string action) {
if (action == "work") {
return true;
}
return false;
}
Clerical (Derived Class)
class Clerical: public Employee {
public:
bool can_hire_and_fire();
void file_papers();
bool has_authority(string str);
};
bool Clerical::has_authority (string action) {
if (action == "paperwork") {
return true;
}
return Employee::has_authority (action);
}
Manager (Derived Class)
class Manager : public Employee {
public:
bool can_hire_and_fire();
bool has_authority (string);
};
bool Manager::has_authority (string action) {
if (action == "managing") {
return true;
}
return Employee::has_authority (action);
}
Main Program
int main(int argc, char** argv) {
Employee *cler = new Clerical();
Employee *man = new Manager();
string actions[3] = {"paperwork", "work", "managing"};
for (int i = 0; i < 3; i++) {
cout << "Managers authority for " << actions[i] << " "
<< man->has_authority (actions[i]) << endl;
cout << "Clerical authority for " << actions[i] << " "
<< cler->has_authority (actions[i]) << endl;
}
}
Overriding in Java
• Java provides a special keyword, super to refer to a
parent class.
• C++ offers no equivalent due to its support of multiple inheritance.
• Otherwise works identically:
• return super.has_authority (action);
• Overriding simplified by virtue of no virtual functions.
Notes on the Chain
• No need for parent classes to define the method.
• Will be passed back up to the most specialised parent that does.
• Scope resolution is used to redirect function calls to
parent classes.
• You can bypass parents if you like, but this is not good practise.
Overriding and Encapsulation
• Does overriding break encapsulation?
• Some say it does, and that child classes should not make calls to
parent classes in this way.
• Inheritance is about specialisation.
• Not replacement.
• Properly used, over-riding enhances encapsulation.
• We don’t need to worry about how our methods will be interpreted,
just that they will be.
Overloading versus Overriding
• Overriding only works as a mechanism of inheritance.
• You can only override a parent’s implementation.
• You can’t override a method in the class in which it is defined.
• Overloading can work in conjunction with overriding.
• The has_authority method we are using is overridden.
• We could provide a second syntax for that that would be overloaded.
• This has implications for clean object design.
Common Overriding Errors
• Mis-spelled function names
• Won’t be picked up when invoked.
• Mismatched parameter lists
• Will overload rather than override.
• Failing to maintain the chain of invocation.
• Make sure you always pass it on.
• Make sure you always pass it on correctly.
• One of the things that super does is resolve to the parent class without you
needing to specify it.
• If you change an inherit chain in C++, you also need to update all
references.
Why Override Functions?
• Information hiding ensures we don’t have access to
private data fields.
• In many cases, we simply can’t configure objects without
overriding.
• No need to excessively duplicate functionality.
• We handle what is new, and let the parent class handle the rest.
• Properly distributes authority through an object
inheritance chain.
Binding and Polymorphism
• All of this is made possible through the use of inheritance
and polymorphism.
• It’s worth spending a few minutes talking about how this is
actually done.
• C++ makes a distinction between the static type of an
object and its dynamic type.
• Shape *myShape = new Circle();
• myShape has a static type of Shape
• myShape has a dynamic type of Circle
Binding and Polymorphism
• The static type is determined at compile time.
• The dynamic type is determined at run-time.
• And it is determined on an ongoing basis.
• This process is known as dynamic binding.
• Dynamic binding has a toll.
• Virtual function lookups at runtime are expensive.
• Virtual functions must be placed and maintained in a virtual function table.
• Static binding is used for functions that are not virtual.
• The function to be executed is decided at compile time and is not changed.
Binding Styles
• There is a trade-off between static and dynamic.
• Java makes all methods virtual by default.
• Static binding is more efficient.
• The compiler can do all sorts of tricks to make it work more
efficiently.
• Dynamic binding is more flexible.
• The interface is consistent but the implementation will change.
Static Methods in Java
• Static methods in Java are the Java implementation of
static binding.
• Static binding is used for static method calls.
• This is why Java has problems with people calling non-
static methods from static contexts.
• The non-static method is virtual.
• The static method is static.
• You can’t even override a static method in Java.
Summary
• Overriding is separate and distinct from overloading.
• Overloading is in addition
• Overriding is instead of
• Maintaining the chain of invocation is important.
• Overriding is predicated on effective use of inheritance
and polymorphism.

Weitere ähnliche Inhalte

Was ist angesagt?

Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Kamlesh Makvana
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)Ritika Sharma
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS ConceptBoopathi K
 
Java package
Java packageJava package
Java packageCS_GDRCST
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programmingSachin Sharma
 
Friend function
Friend functionFriend function
Friend functionzindadili
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaMOHIT AGARWAL
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Sanjit Shaw
 

Was ist angesagt? (20)

Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
 
Friend Function
Friend FunctionFriend Function
Friend Function
 
This pointer
This pointerThis pointer
This pointer
 
Exception handling
Exception handlingException handling
Exception handling
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
 
Java package
Java packageJava package
Java package
 
Inheritance C#
Inheritance C#Inheritance C#
Inheritance C#
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Friend function
Friend functionFriend function
Friend function
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 

Andere mochten auch

2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding2CPP08 - Overloading and Overriding
2CPP08 - Overloading and OverridingMichael Heron
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismrattaj
 
operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cppgourav kottawar
 
C++ overloading
C++ overloadingC++ overloading
C++ overloadingsanya6900
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdmHarshal Misalkar
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overridingJavaTportal
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 
Evaluation
EvaluationEvaluation
EvaluationHuntwah
 
Affordable Taiwan Travel
Affordable Taiwan TravelAffordable Taiwan Travel
Affordable Taiwan TravelMUSTHoover
 

Andere mochten auch (20)

Method overriding in java
Method overriding in javaMethod overriding in java
Method overriding in java
 
2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
 
operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
Pointer in c++ part1
Pointer in c++ part1Pointer in c++ part1
Pointer in c++ part1
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Polymorphism in java, method overloading and method overriding
Polymorphism in java,  method overloading and method overridingPolymorphism in java,  method overloading and method overriding
Polymorphism in java, method overloading and method overriding
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Interface
InterfaceInterface
Interface
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Evaluation
EvaluationEvaluation
Evaluation
 
Affordable Taiwan Travel
Affordable Taiwan TravelAffordable Taiwan Travel
Affordable Taiwan Travel
 
Sfondo
SfondoSfondo
Sfondo
 

Ähnlich wie 2CPP12 - Method Overriding

2CPP11 - Method Overloading
2CPP11 - Method Overloading2CPP11 - Method Overloading
2CPP11 - Method OverloadingMichael Heron
 
11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptxAtharvPotdar2
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1Sherihan Anver
 
2CPP10 - Polymorphism
2CPP10 - Polymorphism2CPP10 - Polymorphism
2CPP10 - PolymorphismMichael Heron
 
A Case Study on Java. Java Presentation
A Case Study on Java. Java Presentation A Case Study on Java. Java Presentation
A Case Study on Java. Java Presentation Ayush Gupta
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticLB Denker
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slidesluqman bawany
 
Performance tuning Grails applications
Performance tuning Grails applicationsPerformance tuning Grails applications
Performance tuning Grails applicationsLari Hotari
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean CodingMetin Ogurlu
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptSanthosh Kumar Srinivasan
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with ReduxFITC
 
Modernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesModernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesiMasters
 

Ähnlich wie 2CPP12 - Method Overriding (20)

2CPP11 - Method Overloading
2CPP11 - Method Overloading2CPP11 - Method Overloading
2CPP11 - Method Overloading
 
11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
 
2CPP10 - Polymorphism
2CPP10 - Polymorphism2CPP10 - Polymorphism
2CPP10 - Polymorphism
 
CPP19 - Revision
CPP19 - RevisionCPP19 - Revision
CPP19 - Revision
 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
 
A Case Study on Java. Java Presentation
A Case Study on Java. Java Presentation A Case Study on Java. Java Presentation
A Case Study on Java. Java Presentation
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Developer testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing FanaticDeveloper testing 101: Become a Testing Fanatic
Developer testing 101: Become a Testing Fanatic
 
2CPP19 - Summation
2CPP19 - Summation2CPP19 - Summation
2CPP19 - Summation
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
 
Performance tuning Grails applications
Performance tuning Grails applicationsPerformance tuning Grails applications
Performance tuning Grails applications
 
Declarative Network Configuration
Declarative Network Configuration Declarative Network Configuration
Declarative Network Configuration
 
Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
Principled And Clean Coding
Principled And Clean CodingPrincipled And Clean Coding
Principled And Clean Coding
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
 
Modernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul JonesModernizing Legacy Applications in PHP, por Paul Jones
Modernizing Legacy Applications in PHP, por Paul Jones
 

Mehr von 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
 

Mehr von 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
 
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
 
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
 

Kürzlich hochgeladen

JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
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
 
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
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 

Kürzlich hochgeladen (20)

JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
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...
 
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
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 

2CPP12 - Method Overriding

  • 2. Introduction • In the last lecture we talked about method overloading. • In this one we are going to talk about method overriding. • The two are often confused, but are entirely different systems. • One is based on the idea of unique identification of methods. • The other is based on being able to specialise behaviours through inheritance.
  • 3. Method Overriding • When we override a method, we specialise it as the child class as part of an inherited relationship. • The usual rules of virtual functions apply here for C++. • Usually what we do here is subtly alter the functionality and then pass the results of our specialisation onto the parent method.
  • 4. Method Overriding • The chain of invocation for a method in C++ depends on its virtuality. • If it is not virtual, the base method gets called always. • If it is virtual, the most specialised implementation gets called. • For virtual methods, we then have control over the chain of invocation. • We can decide how invocations filter up and down the chain.
  • 5. The Chain of Invocation • This is a fancy way of saying ‘which functions get executed when’. • A well over-ridden function will tend to pass function calls back onto their parent classes. • There is nothing to stop you entirely handling a function in the most specialised instance. • It’s generally not very good design. • Violates the principles of encapsulation.
  • 6. Employee (Base Class) class Employee { private: int payscale; public: int query_payscale(); void set_payscale (int p); virtual bool can_hire_and_fire(); virtual bool has_authority (string); }; bool Employee::has_authority (string action) { if (action == "work") { return true; } return false; }
  • 7. Clerical (Derived Class) class Clerical: public Employee { public: bool can_hire_and_fire(); void file_papers(); bool has_authority(string str); }; bool Clerical::has_authority (string action) { if (action == "paperwork") { return true; } return Employee::has_authority (action); }
  • 8. Manager (Derived Class) class Manager : public Employee { public: bool can_hire_and_fire(); bool has_authority (string); }; bool Manager::has_authority (string action) { if (action == "managing") { return true; } return Employee::has_authority (action); }
  • 9. Main Program int main(int argc, char** argv) { Employee *cler = new Clerical(); Employee *man = new Manager(); string actions[3] = {"paperwork", "work", "managing"}; for (int i = 0; i < 3; i++) { cout << "Managers authority for " << actions[i] << " " << man->has_authority (actions[i]) << endl; cout << "Clerical authority for " << actions[i] << " " << cler->has_authority (actions[i]) << endl; } }
  • 10. Overriding in Java • Java provides a special keyword, super to refer to a parent class. • C++ offers no equivalent due to its support of multiple inheritance. • Otherwise works identically: • return super.has_authority (action); • Overriding simplified by virtue of no virtual functions.
  • 11. Notes on the Chain • No need for parent classes to define the method. • Will be passed back up to the most specialised parent that does. • Scope resolution is used to redirect function calls to parent classes. • You can bypass parents if you like, but this is not good practise.
  • 12. Overriding and Encapsulation • Does overriding break encapsulation? • Some say it does, and that child classes should not make calls to parent classes in this way. • Inheritance is about specialisation. • Not replacement. • Properly used, over-riding enhances encapsulation. • We don’t need to worry about how our methods will be interpreted, just that they will be.
  • 13. Overloading versus Overriding • Overriding only works as a mechanism of inheritance. • You can only override a parent’s implementation. • You can’t override a method in the class in which it is defined. • Overloading can work in conjunction with overriding. • The has_authority method we are using is overridden. • We could provide a second syntax for that that would be overloaded. • This has implications for clean object design.
  • 14. Common Overriding Errors • Mis-spelled function names • Won’t be picked up when invoked. • Mismatched parameter lists • Will overload rather than override. • Failing to maintain the chain of invocation. • Make sure you always pass it on. • Make sure you always pass it on correctly. • One of the things that super does is resolve to the parent class without you needing to specify it. • If you change an inherit chain in C++, you also need to update all references.
  • 15. Why Override Functions? • Information hiding ensures we don’t have access to private data fields. • In many cases, we simply can’t configure objects without overriding. • No need to excessively duplicate functionality. • We handle what is new, and let the parent class handle the rest. • Properly distributes authority through an object inheritance chain.
  • 16. Binding and Polymorphism • All of this is made possible through the use of inheritance and polymorphism. • It’s worth spending a few minutes talking about how this is actually done. • C++ makes a distinction between the static type of an object and its dynamic type. • Shape *myShape = new Circle(); • myShape has a static type of Shape • myShape has a dynamic type of Circle
  • 17. Binding and Polymorphism • The static type is determined at compile time. • The dynamic type is determined at run-time. • And it is determined on an ongoing basis. • This process is known as dynamic binding. • Dynamic binding has a toll. • Virtual function lookups at runtime are expensive. • Virtual functions must be placed and maintained in a virtual function table. • Static binding is used for functions that are not virtual. • The function to be executed is decided at compile time and is not changed.
  • 18. Binding Styles • There is a trade-off between static and dynamic. • Java makes all methods virtual by default. • Static binding is more efficient. • The compiler can do all sorts of tricks to make it work more efficiently. • Dynamic binding is more flexible. • The interface is consistent but the implementation will change.
  • 19. Static Methods in Java • Static methods in Java are the Java implementation of static binding. • Static binding is used for static method calls. • This is why Java has problems with people calling non- static methods from static contexts. • The non-static method is virtual. • The static method is static. • You can’t even override a static method in Java.
  • 20. Summary • Overriding is separate and distinct from overloading. • Overloading is in addition • Overriding is instead of • Maintaining the chain of invocation is important. • Overriding is predicated on effective use of inheritance and polymorphism.