SlideShare a Scribd company logo
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.

More Related Content

What's hot

Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
Jenish Patel
 
Java Tokens
Java  TokensJava  Tokens
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming
Kamal Acharya
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
Kuppusamy P
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
Nochiketa Chakraborty
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Functions in c
Functions in cFunctions in c
Functions in c
sunila tharagaturi
 
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
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
Ritika Sharma
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
Thooyavan Venkatachalam
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
Ahsan Raja
 
inline function
inline function inline function
inline function
imran khan
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Paumil Patel
 

What's hot (20)

Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Expression and Operartor In C Programming
Expression and Operartor In C Programming Expression and Operartor In C Programming
Expression and Operartor In C Programming
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Inline function
Inline functionInline function
Inline function
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Functions in c
Functions in cFunctions in c
Functions in c
 
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
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
inline function
inline function inline function
inline function
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 

Viewers also liked

Method overriding in java
Method overriding in javaMethod overriding in java
Method overriding in java
One97 Communications Limited
 
2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding2CPP08 - Overloading and Overriding
2CPP08 - Overloading and Overriding
Michael Heron
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
pointers,virtual functions and polymorphism
pointers,virtual functions and polymorphismpointers,virtual functions and polymorphism
pointers,virtual functions and polymorphism
rattaj
 
Function overloading
Function overloadingFunction overloading
Function overloading
Selvin Josy Bai Somu
 
operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
gourav kottawar
 
C++ Programming
C++ ProgrammingC++ Programming
C++ overloading
C++ overloadingC++ overloading
C++ overloading
sanya6900
 
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
Harshal Misalkar
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Rajat Busheheri
 
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 overriding
JavaTportal
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
Chaand Sheikh
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
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 Travel
MUSTHoover
 

Viewers also liked (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++
 
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
 

Similar to 2CPP12 - Method Overriding

2CPP11 - Method Overloading
2CPP11 - Method Overloading2CPP11 - Method Overloading
2CPP11 - Method Overloading
Michael Heron
 
11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx
AtharvPotdar2
 
Java interview questions 1
Java interview questions 1Java interview questions 1
Java interview questions 1
Sherihan Anver
 
2CPP10 - Polymorphism
2CPP10 - Polymorphism2CPP10 - Polymorphism
2CPP10 - Polymorphism
Michael Heron
 
CPP19 - Revision
CPP19 - RevisionCPP19 - Revision
CPP19 - Revision
Michael Heron
 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
SURBHI SAROHA
 
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 Implicit
Martin Odersky
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
Martin 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 Fanatic
LB Denker
 
2CPP19 - Summation
2CPP19 - Summation2CPP19 - Summation
2CPP19 - Summation
Michael Heron
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
luqman bawany
 
Performance tuning Grails applications
Performance tuning Grails applicationsPerformance tuning Grails applications
Performance tuning Grails applications
Lari Hotari
 
Declarative Network Configuration
Declarative Network Configuration Declarative Network Configuration
Declarative Network Configuration
Salesforce Engineering
 
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 Coding
Metin Ogurlu
 
Introduction to Design Patterns in Javascript
Introduction to Design Patterns in JavascriptIntroduction to Design Patterns in Javascript
Introduction to Design Patterns in Javascript
Santhosh Kumar Srinivasan
 
Building React Applications with Redux
Building React Applications with ReduxBuilding React Applications with Redux
Building React Applications with Redux
FITC
 
Design p atterns
Design p atternsDesign p atterns
Design p atterns
Amr Abd El Latief
 
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
iMasters
 

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

More from Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
Michael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
Michael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
Michael 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 Support
Michael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
Michael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
Michael Heron
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
Michael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
Michael Heron
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
Michael 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 Representation
Michael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
Michael Heron
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
Michael Heron
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
Michael Heron
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Michael Heron
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
Michael Heron
 

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

Recently uploaded

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 

Recently uploaded (20)

Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 

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.