Polymorphism in C++ 24th Aug 2007. Overview Polymorphism means “Many forms” OO Purists – “Only virtual methods” Liberal C++ guys – Either virtual methods.

Slides:



Advertisements
Similar presentations
CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
Advertisements

Generics. DCS – SWC 2 Generics In many situations, we want a certain functionality to work for a variety of types Typical example: we want to be able.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
ITEC200 – Week03 Inheritance and Class Hierarchies.
Object-Oriented PHP (1)
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
C++ Training Datascope Lawrence D’Antonio Lecture 3 An Overview of C++
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Design Patterns Ref : Chapter 15 Bennett et al. useful groups of collaborating classes that provide a solution to commonly occuring problems. provide.
UML Class Diagrams: Basic Concepts. Objects –The purpose of class modeling is to describe objects. –An object is a concept, abstraction or thing that.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
(…A FEW OF THEM) C++ DESIGN PATTERNS. WHAT ARE THEY? Commonly occurring constructs Could be part of good software engineering Not universally agreed Good.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
JAVA Introduction ● One of the main JAVA design goal is reducing complexity for programmer – Development time is half or less comparing to equivalent C++
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
OOP and Dynamic Method Binding Chapter 9. Object Oriented Programming Skipping most of this chapter Focus on 9.4, Dynamic method binding – Polymorphism.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
1 Computer Science 340 Software Design & Testing Inheritance.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Programming in Java CSCI-2220 Object Oriented Programming.
CSCI-383 Object-Oriented Programming & Design Lecture 18.
Chapter 10 Classes and Objects In-Depth. Chapter 10 A class provides the foundation for creating specific objects, each of which shares the general attributes,
CS212: Object Oriented Analysis and Design Lecture 17: Virtual Functions.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Overview of C++ Templates
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
CPS Inheritance and the Yahtzee program l In version of Yahtzee given previously, scorecard.h held information about every score-card entry, e.g.,
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Overview of C++ Polymorphism
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
Classes - Part II (revisited) n Constant objects and member functions n Definition Form of Member Functions n friend functions and friend classes n Constructors.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
CSCE 240 – Intro to Software Engineering Lecture 3.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Copyright © Jim Fawcett Spring 2017
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
7. Inheritance and Polymorphism
Inheritance and Polymorphism
Object-Oriented Programming & Design Lecture 18 Martin van Bommel
Object-Oriented Programming
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
CISC/CMPE320 - Prof. McLeod
C++ Object Oriented 1.
Presentation transcript:

Polymorphism in C++ 24th Aug 2007

Overview 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

Kinds of Polymorphism 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

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 func(T* pThreadingPolicy) { pThreadingPolicy->lock(); };

Any of them works - Contd 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

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

Compile time 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...)

Why all the excitement about templates? Templates – –Buy us generality in software, without the ‘Abstraction penalty’ –Are type safe –Are non-intrusive –Allow both reference and value semantics unlike virtuals

Design of reusable data structures – Inheritance or Templates? Value or Reference semantics, both allowed Reference semantics only (leaks, crashes..) 4 Non-IntrusiveIntrusive (put an int/char inside a class and derive from base) 3 Type safeNon type-safe (Crash!) 2 FasterSlower (virtuals)1 Template based approach Inheritance based approach Index

Sure choice - Templates 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

Why inheritance then? 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

Choosing your polymorphism 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)

Vanilla or Strawberry? I think I’ll have both 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

Singleton using the van-berry flavor 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]

Object counter 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]

Cost of runtime polymorphism 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’

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::~Base Pointer to Base::func2 Pointer to Base::func1 vtable for the Derived class Pointer to Derived::~Derived Pointer to Base::func2 Pointer to Derived::func1 vtable for the Base class

Illustration (Contd)

What happens at runtime? 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

So, what’s the cost? 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 link element objects, each containing 4 bytes extra!)

Is that all? Well, this gets worse when MI (Multiple Inheritance is used) Now, the deal is 15-20% overhead for MI for method defined in the 2 nd 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

Cost of compile time polymorphism 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)

Template code bloat 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, list 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 (Contd) 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’

Longer compilation time 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

Workaround 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

Summary Prefer inheritance when –You want to reuse code/structure from the base class –You want to develop OO frameworks which need to store heterogeneous elements in their data structures Prefer templates when –You want generic data structures and algorithms –Where Speed is important