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

Contenu connexe

Tendances

Strings in C language
Strings in C languageStrings in C language
Strings in C languageP M Patil
 
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
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java yash jain
 
Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 

Tendances (20)

Strings in C language
Strings in C languageStrings in C language
Strings in C language
 
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
 
Ternary operator
Ternary operatorTernary operator
Ternary operator
 
Procedural programming
Procedural programmingProcedural programming
Procedural programming
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
OOP and FP
OOP and FPOOP and FP
OOP and FP
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Function in c
Function in cFunction in c
Function in c
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Control Statement programming
Control Statement programmingControl Statement programming
Control Statement programming
 

En vedette

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

En vedette (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
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
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++
 
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
 

Similaire à 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
 

Similaire à 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
 

Plus de Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 

Plus de Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
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
 

Dernier

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
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
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
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
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
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
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
 
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
 
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.
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 

Dernier (20)

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...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
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 ...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
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...
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
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
 
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
 
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 ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 

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.