SlideShare a Scribd company logo
24th Aug 2007
Polymorphism means “Many forms”
OO Purists – “Only virtual methods”
Liberal C++ guys – Either virtual methods (Behavior), or templates (Types), or
even function overloading for that matter (Behavior)
Generally accepted – virtual method based, and template based
OVERVIEW
Runtime/Dynamic polymorphism (Based on virtual methods)
Compile time/Static polymorphism (Based on templates)
These 2 are largely orthogonal techniques, but many ways where one could be
replaced with the other…and that’s where the confusion
KINDS OF POLYMORPHISM
ANY OF THEM WORKS – EXAMPLE
// Using virtual method based polymorphism
// lock is a virtual method. SingleThreading and Multi-
threading are 2 derived classes which define lock()
differently
void func(BaseThreadingPolicy * pThreadingPolicy)
{
pThreadingPolicy->lock();
};
// Using template based polymorphism
SingleThreading and Multi-threading both implement a lock()
method, but the needn’t have any virtual methods, nor do
they need to derive from a common base class
template <class T> func(T* pThreadingPolicy)
{
pThreadingPolicy->lock();
};
In the previous slide we have shown that templates aren’t restricted to
polymorphism of type alone, but they also can be used for polymorphism of
behavior
In fact the template version in the previous example yields much faster code than
the virtual method equivalent
Much prevailing confusion about which technique to use in what situation
ANY OF THEM WORKS - CONTD
Runtime binding between abstract type and concrete type
Enforces a common interface for all derived types via the base class
Enforces an ‘Is-A’ relationship
Used extensively in OO frameworks
Templates eating into parts of its territory
RUNTIME POLYMORPHISM
Compile time binding between abstract type and concrete
type
Concrete types need not belong to the same inheritance
hierarchy. They just need to meet the ‘Constraints’
imposed by the generic type. So, more generic than the
virtuals
Foundation of ‘Generic programming’ or programming
based on ‘Concepts’ (Eg: STL)
A very ‘Happening area’ in C++ right now (See TR1,
Boost, C++0x...)
COMPILE TIME POLYMORPHISM
Templates –
Buy us generality in software, without the ‘Abstraction penalty’
Are type safe
Are non-intrusive
Allow both reference and value semantics unlike virtuals
WHY ALL THE
EXCITEMENT
ABOUT
TEMPLATES?
DESIGN OF REUSABLE DATA
STRUCTURES – INHERITANCE OR
TEMPLATES?
IndexIndex Inheritance basedInheritance based
approachapproach
Template based approachTemplate based approach
1 Slower (virtuals) Faster
2 Non type-safe
(Crash!)
Type safe
3 Intrusive (put an
int/char inside a class
and derive from base)
Non-Intrusive
4 Reference semantics
only (leaks, crashes..)
Value or Reference
semantics, both allowed
So, templates lead to ‘Faster, Safer, and Easier to reuse’ data structures than
inheritance
Using inheritance for designing generic data structures, is a common mistake in
C++
Dates back to days where compiler support was bad for templates
SURE CHOICE - TEMPLATES
Code and structure reuse from base classes
OO Frameworks
Framework implementation requires ‘Heterogeneous containers’
Reactor example
Often depend on polymorphic return types
Factory example
Can’t do that with templates
WHY INHERITANCE THEN?
Don’t overuse inheritance (Implementing data structures using inheritance is an
example of misuse of inheritance)
Evaluate if your design could be done using templates, they are faster and safer
than virtuals.
Read up on templates and be aware of its pitfalls (Another class of mine will deal
with that)
CHOOSING YOUR
POLYMORPHISM
Templates and Inheritance can be combined sometimes
Eg 1: Singleton pattern implementation
Eg 2: Reusable object counter
Eg 3: Reducing template code bloat
Weakness of inheritance – Base classes don’t know the
type of their derived classes
Static attributes in base class are ‘Shared’
Weakness of templates – They don’t lead to an ‘Is-A’
relationship
VANILLA OR
STRAWBERRY? I
THINK I’LL
HAVE BOTH
Best of both worlds
Have base class know the derived class type by using templates [So, getInstance in the
base class is able to create a derived class instance]
Enforce ‘Is-A’ relationship using inheritance [Eg: Make ctor private in the base class, so
nobody can instantiate a derived class instance as well]
SINGLETON
USING THE VAN-
BERRY FLAVOR
Synergy again
Base classes need to share the static attributes
Use templates to get over that issue – One base class generated for each derived class
Use inheritance for the ‘Is-A’ relationship [Whenever the class ctor is called, the base class
ctor is called, likewise for the dtor, increment and decrement operations happen
automatically]
OBJECT COUNTER
Each class that has a virtual method has an associated
‘vtable’
A ‘vtable’ is just an array of function pointers containing
pointers to virtual method implementations for that class
Each object of any such class, has a pointer to the
associated vtable
The compiler creates the required vtables and initializes
each object to point to the associated vtable all ‘Under the
hood’
COST OF RUNTIME
POLYMORPHISM
ILLUSTRATION
Class Base
{
public:
Base();
virtual void func1();
virtual void func2();
virtual ~Base():
};
Class Derived
{
public:
Derived();
virtual void func1();
virtual ~Derived();
};
ILLUSTRATION (CONTD)
Pointer to Base::func1
Pointer to Base::func2
Pointer to Base::~Base
vtable for the Derived class
Pointer to Derived::func1
Pointer to Base::func2
Pointer to Derived::~Derived
vtable for the Base class
ILLUSTRATION (CONTD)
The compiler would have converted all your virtual method calls
Your call: pDerived->func2();
It’s become: (*pDerived->vptr[1])(pDerived)
As we see above, the vptr stored by the compiler in the derived object is looked
up, an offset (+1) added to get to the second virtual method in the class, and the
function is called
WHAT HAPPENS AT RUNTIME?
Direct cost – vtable lookup (Put at about 5-10% overhead as opposed to non-
virtual methods)
Indirect cost –
Cannot inline virtual methods (Makes a big difference)
Each objects needs to store extra pointer (An issue for fine grained objects – say 1000000
link element objects, each containing 4 bytes extra!)
SO, WHAT’S THE COST?
Well, this gets worse when MI (Multiple Inheritance is
used)
Now, the deal is 15-20% overhead for MI for method
defined in the 2nd
and onwards base class. There’s no
penalty for methods in the first base class we derive from
Ensure your most frequently called methods are from the
FIRST base class you derive from if you use MI, order
your base classes accordingly
IS THAT ALL?
ZERO runtime cost (Abstraction without abstraction penalty)
However …
Coders not aware of how templates work ‘Under the hood’ end up creating code bloat
Developer turn around time increased due to longer compiles (This could be avoided too)
COST OF
COMPILE TIME
POLYMORPHISM
Code bloat happens because compilers cannot do
‘Commonality and variability analysis’
If the code body is the same for a set of template
argument values, the compiler fails to see that and
generates multiple classes for each argument value
Eg: list<int *>, list<char *, list<MyClass*> all of these
may have the same underlying implementation of a
‘Container of POINTERS’, but the compiler generates 3
different class definitions for these
TEMPLATE CODE BLOAT
A coder who knows this, does the following
Give a partial template specialization for POINTER types
Have that derive from a void * based container which has most of the implementation in
it
This specialized class will have simple inline methods that ‘Delegate’ to the base class and
gets work done
TEMPLATE CODE BLOAT
(CONTD)
So, we get the following result –
The thin inline wrappers in the specialized class offer type safety
Majority of the code body is in the non-template base class and hence no duplication of it
The thin wrappers are all inline hence no performance overhead as well
This is called the ‘Hoisting idiom’
TEMPLATE CODE BLOAT
(CONTD)
Happens mainly because the template method definitions have to be in the
header file
They may in turn pull in other headers and hence lead to large include sizes and
hence more compile time
More work to the compiler in case one uses template meta-programming
LONGER COMPILATION TIME
To reduce compile times, we can use the ‘Explicit instantiation’ technique in
cases where large includes are warranted
Here basically you give the method body in a .cpp file and put only the template
class definition in the .h file, but explicitly instantiate the template in the .cpp file
where the methods are defined for all types expected
WORKAROUND

More Related Content

What's hot

Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
Elizabeth alexander
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oop
MustafaIbrahimy
 
C#
C#C#
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
suraj pandey
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
harsh kothari
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثة
Mahmoud Alfarra
 
Static keyword u.s ass.(2)
Static keyword u.s ass.(2)Static keyword u.s ass.(2)
Static keyword u.s ass.(2)
Syed Umair
 
Abstract method
Abstract methodAbstract method
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
Mahmoud Alfarra
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
Spotle.ai
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
Mahmoud Alfarra
 
‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
Mahmoud Alfarra
 
Polymorphism
PolymorphismPolymorphism
PolymorphismKumar
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
tigerwarn
 
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Ivano Malavolta
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
malathip12
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
Pritom Chaki
 
Modeling objects interaction via UML sequence diagrams [Software Modeling] [...
Modeling objects interaction via UML sequence diagrams  [Software Modeling] [...Modeling objects interaction via UML sequence diagrams  [Software Modeling] [...
Modeling objects interaction via UML sequence diagrams [Software Modeling] [...
Ivano Malavolta
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
Niranjan Sarade
 

What's hot (20)

Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Polymorphism in oop
Polymorphism in oopPolymorphism in oop
Polymorphism in oop
 
C#
C#C#
C#
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
البرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثةالبرمجة الهدفية بلغة جافا - الوراثة
البرمجة الهدفية بلغة جافا - الوراثة
 
Static keyword u.s ass.(2)
Static keyword u.s ass.(2)Static keyword u.s ass.(2)
Static keyword u.s ass.(2)
 
Abstract method
Abstract methodAbstract method
Abstract method
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Abstract Class Presentation
Abstract Class PresentationAbstract Class Presentation
Abstract Class Presentation
 
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
Modeling objects interaction via UML sequence diagrams [Software Design] [Com...
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
 
Modeling objects interaction via UML sequence diagrams [Software Modeling] [...
Modeling objects interaction via UML sequence diagrams  [Software Modeling] [...Modeling objects interaction via UML sequence diagrams  [Software Modeling] [...
Modeling objects interaction via UML sequence diagrams [Software Modeling] [...
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
 

Similar to Static and dynamic polymorphism

Static and dynamic polymorphism
Static and dynamic polymorphismStatic and dynamic polymorphism
Static and dynamic polymorphism
sanjay joshi
 
C++ Basics
C++ BasicsC++ Basics
C++ Basics
Himanshu Sharma
 
Code Metrics
Code MetricsCode Metrics
Code Metrics
Attila Bertók
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
Ranjith Sekar
 
Design patterns(red)
Design patterns(red)Design patterns(red)
Design patterns(red)
Fahad A. Shaikh
 
Unit 3
Unit 3Unit 3
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
nicolbiden
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
Nadeesha Thilakarathne
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
Shashwat Shriparv
 
C# - Igor Ralić
C# - Igor RalićC# - Igor Ralić
Evolve Your Code
Evolve Your CodeEvolve Your Code
Evolve Your Code
RookieOne
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
dn
 
Net Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdfNet Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdf
PavanNarne1
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
SamuelAnsong6
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
brada
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
Mohamed Essam
 

Similar to Static and dynamic polymorphism (20)

Static and dynamic polymorphism
Static and dynamic polymorphismStatic and dynamic polymorphism
Static and dynamic polymorphism
 
C++ Basics
C++ BasicsC++ Basics
C++ Basics
 
Code Metrics
Code MetricsCode Metrics
Code Metrics
 
OOPs in Java
OOPs in JavaOOPs in Java
OOPs in Java
 
Design patterns(red)
Design patterns(red)Design patterns(red)
Design patterns(red)
 
Unit 3
Unit 3Unit 3
Unit 3
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Andy On Closures
Andy On ClosuresAndy On Closures
Andy On Closures
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
 
C# - Igor Ralić
C# - Igor RalićC# - Igor Ralić
C# - Igor Ralić
 
Evolve Your Code
Evolve Your CodeEvolve Your Code
Evolve Your Code
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Net Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdfNet Interview-Questions 1 - 16.pdf
Net Interview-Questions 1 - 16.pdf
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 

More from sanjay joshi

Ccna security
Ccna security Ccna security
Ccna security
sanjay joshi
 
Array in c language
Array in c languageArray in c language
Array in c language
sanjay joshi
 
Introduction to c programming language
Introduction to c programming languageIntroduction to c programming language
Introduction to c programming language
sanjay joshi
 
Cloud computing
Cloud computingCloud computing
Cloud computing
sanjay joshi
 
Embeded system
Embeded systemEmbeded system
Embeded system
sanjay joshi
 
Distributed database
Distributed databaseDistributed database
Distributed database
sanjay joshi
 
Vb and asp.net
Vb and asp.netVb and asp.net
Vb and asp.net
sanjay joshi
 
Angular js
Angular jsAngular js
Angular js
sanjay joshi
 
introduction to c programming language
introduction to c programming languageintroduction to c programming language
introduction to c programming language
sanjay joshi
 
Oops in php
Oops in phpOops in php
Oops in php
sanjay joshi
 
Cascading Style Sheets
Cascading Style SheetsCascading Style Sheets
Cascading Style Sheets
sanjay joshi
 
Css3 responsive
Css3 responsive Css3 responsive
Css3 responsive
sanjay joshi
 
Html ppt
Html pptHtml ppt
Html ppt
sanjay joshi
 
Java script
Java scriptJava script
Java script
sanjay joshi
 
Data Structure And Queue
Data Structure And Queue Data Structure And Queue
Data Structure And Queue
sanjay joshi
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
sanjay joshi
 
Angularjs
AngularjsAngularjs
Angularjs
sanjay joshi
 
Visual basic
Visual basicVisual basic
Visual basic
sanjay joshi
 
Distributed database
Distributed databaseDistributed database
Distributed database
sanjay joshi
 
Embeded system
Embeded systemEmbeded system
Embeded system
sanjay joshi
 

More from sanjay joshi (20)

Ccna security
Ccna security Ccna security
Ccna security
 
Array in c language
Array in c languageArray in c language
Array in c language
 
Introduction to c programming language
Introduction to c programming languageIntroduction to c programming language
Introduction to c programming language
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 
Embeded system
Embeded systemEmbeded system
Embeded system
 
Distributed database
Distributed databaseDistributed database
Distributed database
 
Vb and asp.net
Vb and asp.netVb and asp.net
Vb and asp.net
 
Angular js
Angular jsAngular js
Angular js
 
introduction to c programming language
introduction to c programming languageintroduction to c programming language
introduction to c programming language
 
Oops in php
Oops in phpOops in php
Oops in php
 
Cascading Style Sheets
Cascading Style SheetsCascading Style Sheets
Cascading Style Sheets
 
Css3 responsive
Css3 responsive Css3 responsive
Css3 responsive
 
Html ppt
Html pptHtml ppt
Html ppt
 
Java script
Java scriptJava script
Java script
 
Data Structure And Queue
Data Structure And Queue Data Structure And Queue
Data Structure And Queue
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Angularjs
AngularjsAngularjs
Angularjs
 
Visual basic
Visual basicVisual basic
Visual basic
 
Distributed database
Distributed databaseDistributed database
Distributed database
 
Embeded system
Embeded systemEmbeded system
Embeded system
 

Recently uploaded

Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 

Recently uploaded (20)

Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 

Static and dynamic polymorphism

  • 2. Polymorphism means “Many forms” OO Purists – “Only virtual methods” Liberal C++ guys – Either virtual methods (Behavior), or templates (Types), or even function overloading for that matter (Behavior) Generally accepted – virtual method based, and template based OVERVIEW
  • 3. Runtime/Dynamic polymorphism (Based on virtual methods) Compile time/Static polymorphism (Based on templates) These 2 are largely orthogonal techniques, but many ways where one could be replaced with the other…and that’s where the confusion KINDS OF POLYMORPHISM
  • 4. ANY OF THEM WORKS – EXAMPLE // Using virtual method based polymorphism // lock is a virtual method. SingleThreading and Multi- threading are 2 derived classes which define lock() differently void func(BaseThreadingPolicy * pThreadingPolicy) { pThreadingPolicy->lock(); }; // Using template based polymorphism SingleThreading and Multi-threading both implement a lock() method, but the needn’t have any virtual methods, nor do they need to derive from a common base class template <class T> func(T* pThreadingPolicy) { pThreadingPolicy->lock(); };
  • 5. In the previous slide we have shown that templates aren’t restricted to polymorphism of type alone, but they also can be used for polymorphism of behavior In fact the template version in the previous example yields much faster code than the virtual method equivalent Much prevailing confusion about which technique to use in what situation ANY OF THEM WORKS - CONTD
  • 6. Runtime binding between abstract type and concrete type Enforces a common interface for all derived types via the base class Enforces an ‘Is-A’ relationship Used extensively in OO frameworks Templates eating into parts of its territory RUNTIME POLYMORPHISM
  • 7. Compile time binding between abstract type and concrete type Concrete types need not belong to the same inheritance hierarchy. They just need to meet the ‘Constraints’ imposed by the generic type. So, more generic than the virtuals Foundation of ‘Generic programming’ or programming based on ‘Concepts’ (Eg: STL) A very ‘Happening area’ in C++ right now (See TR1, Boost, C++0x...) COMPILE TIME POLYMORPHISM
  • 8. Templates – Buy us generality in software, without the ‘Abstraction penalty’ Are type safe Are non-intrusive Allow both reference and value semantics unlike virtuals WHY ALL THE EXCITEMENT ABOUT TEMPLATES?
  • 9. DESIGN OF REUSABLE DATA STRUCTURES – INHERITANCE OR TEMPLATES? IndexIndex Inheritance basedInheritance based approachapproach Template based approachTemplate based approach 1 Slower (virtuals) Faster 2 Non type-safe (Crash!) Type safe 3 Intrusive (put an int/char inside a class and derive from base) Non-Intrusive 4 Reference semantics only (leaks, crashes..) Value or Reference semantics, both allowed
  • 10. So, templates lead to ‘Faster, Safer, and Easier to reuse’ data structures than inheritance Using inheritance for designing generic data structures, is a common mistake in C++ Dates back to days where compiler support was bad for templates SURE CHOICE - TEMPLATES
  • 11. Code and structure reuse from base classes OO Frameworks Framework implementation requires ‘Heterogeneous containers’ Reactor example Often depend on polymorphic return types Factory example Can’t do that with templates WHY INHERITANCE THEN?
  • 12. Don’t overuse inheritance (Implementing data structures using inheritance is an example of misuse of inheritance) Evaluate if your design could be done using templates, they are faster and safer than virtuals. Read up on templates and be aware of its pitfalls (Another class of mine will deal with that) CHOOSING YOUR POLYMORPHISM
  • 13. Templates and Inheritance can be combined sometimes Eg 1: Singleton pattern implementation Eg 2: Reusable object counter Eg 3: Reducing template code bloat Weakness of inheritance – Base classes don’t know the type of their derived classes Static attributes in base class are ‘Shared’ Weakness of templates – They don’t lead to an ‘Is-A’ relationship VANILLA OR STRAWBERRY? I THINK I’LL HAVE BOTH
  • 14. Best of both worlds Have base class know the derived class type by using templates [So, getInstance in the base class is able to create a derived class instance] Enforce ‘Is-A’ relationship using inheritance [Eg: Make ctor private in the base class, so nobody can instantiate a derived class instance as well] SINGLETON USING THE VAN- BERRY FLAVOR
  • 15. Synergy again Base classes need to share the static attributes Use templates to get over that issue – One base class generated for each derived class Use inheritance for the ‘Is-A’ relationship [Whenever the class ctor is called, the base class ctor is called, likewise for the dtor, increment and decrement operations happen automatically] OBJECT COUNTER
  • 16. Each class that has a virtual method has an associated ‘vtable’ A ‘vtable’ is just an array of function pointers containing pointers to virtual method implementations for that class Each object of any such class, has a pointer to the associated vtable The compiler creates the required vtables and initializes each object to point to the associated vtable all ‘Under the hood’ COST OF RUNTIME POLYMORPHISM
  • 17. ILLUSTRATION Class Base { public: Base(); virtual void func1(); virtual void func2(); virtual ~Base(): }; Class Derived { public: Derived(); virtual void func1(); virtual ~Derived(); };
  • 18. ILLUSTRATION (CONTD) Pointer to Base::func1 Pointer to Base::func2 Pointer to Base::~Base vtable for the Derived class Pointer to Derived::func1 Pointer to Base::func2 Pointer to Derived::~Derived vtable for the Base class
  • 20. The compiler would have converted all your virtual method calls Your call: pDerived->func2(); It’s become: (*pDerived->vptr[1])(pDerived) As we see above, the vptr stored by the compiler in the derived object is looked up, an offset (+1) added to get to the second virtual method in the class, and the function is called WHAT HAPPENS AT RUNTIME?
  • 21. Direct cost – vtable lookup (Put at about 5-10% overhead as opposed to non- virtual methods) Indirect cost – Cannot inline virtual methods (Makes a big difference) Each objects needs to store extra pointer (An issue for fine grained objects – say 1000000 link element objects, each containing 4 bytes extra!) SO, WHAT’S THE COST?
  • 22. Well, this gets worse when MI (Multiple Inheritance is used) Now, the deal is 15-20% overhead for MI for method defined in the 2nd and onwards base class. There’s no penalty for methods in the first base class we derive from Ensure your most frequently called methods are from the FIRST base class you derive from if you use MI, order your base classes accordingly IS THAT ALL?
  • 23. ZERO runtime cost (Abstraction without abstraction penalty) However … Coders not aware of how templates work ‘Under the hood’ end up creating code bloat Developer turn around time increased due to longer compiles (This could be avoided too) COST OF COMPILE TIME POLYMORPHISM
  • 24. Code bloat happens because compilers cannot do ‘Commonality and variability analysis’ If the code body is the same for a set of template argument values, the compiler fails to see that and generates multiple classes for each argument value Eg: list<int *>, list<char *, list<MyClass*> all of these may have the same underlying implementation of a ‘Container of POINTERS’, but the compiler generates 3 different class definitions for these TEMPLATE CODE BLOAT
  • 25. A coder who knows this, does the following Give a partial template specialization for POINTER types Have that derive from a void * based container which has most of the implementation in it This specialized class will have simple inline methods that ‘Delegate’ to the base class and gets work done TEMPLATE CODE BLOAT (CONTD)
  • 26. So, we get the following result – The thin inline wrappers in the specialized class offer type safety Majority of the code body is in the non-template base class and hence no duplication of it The thin wrappers are all inline hence no performance overhead as well This is called the ‘Hoisting idiom’ TEMPLATE CODE BLOAT (CONTD)
  • 27. Happens mainly because the template method definitions have to be in the header file They may in turn pull in other headers and hence lead to large include sizes and hence more compile time More work to the compiler in case one uses template meta-programming LONGER COMPILATION TIME
  • 28. To reduce compile times, we can use the ‘Explicit instantiation’ technique in cases where large includes are warranted Here basically you give the method body in a .cpp file and put only the template class definition in the .h file, but explicitly instantiate the template in the .cpp file where the methods are defined for all types expected WORKAROUND