SlideShare uma empresa Scribd logo
1 de 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.

Mais conteúdo relacionado

Mais procurados

ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVASAGARDAVE29
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Sanjit Shaw
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Fatima Kate Tanay
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptxParvizMirzayev2
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in JavaJava2Blog
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in JavaKurapati Vishwak
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in javaVishnu Suresh
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In JavaSpotle.ai
 
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
 

Mais procurados (20)

Java constructors
Java constructorsJava constructors
Java constructors
 
ArrayList in JAVA
ArrayList in JAVAArrayList in JAVA
ArrayList in JAVA
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)Passing an Array to a Function (ICT Programming)
Passing an Array to a Function (ICT Programming)
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptx
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in Java
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Java packages
Java packagesJava packages
Java packages
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Pointers
PointersPointers
Pointers
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
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
 

Destaque

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

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

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

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

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

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

Último

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
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
 
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
 
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
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
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
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
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
 
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
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 

Último (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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 ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
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
 
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
 
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...
 
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
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
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...
 
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
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
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
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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
 
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
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 

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.