Static and Dynamic polymorphism in C++

73,705 views

Published on

This slide examines the cost/benefits of both static and dynamic polymorphism in C++

Published in: Technology, Business
2 Comments
28 Likes
Statistics
Notes
  • #include
    void main ()
    {
    cout<<'thank you very much';
    }
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • A good quick intro to dynamic polymorphism, Provides enough valid points to consider polymorphism by templates rather by virtuals in some scenarios.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
73,705
On SlideShare
0
From Embeds
0
Number of Embeds
610
Actions
Shares
0
Downloads
1,493
Comments
2
Likes
28
Embeds 0
No embeds

No notes for slide

Static and Dynamic polymorphism in C++

  1. 1. Polymorphism in C++ 24th Aug 2007
  2. 2. Overview <ul><li>Polymorphism means “Many forms” </li></ul><ul><li>OO Purists – “Only virtual methods” </li></ul><ul><li>Liberal C++ guys – Either virtual methods (Behavior), or templates (Types), or even function overloading for that matter (Behavior) </li></ul><ul><li>Generally accepted – virtual method based, and template based </li></ul>
  3. 3. Kinds of Polymorphism <ul><li>Runtime/Dynamic polymorphism (Based on virtual methods) </li></ul><ul><li>Compile time/Static polymorphism (Based on templates) </li></ul><ul><li>These 2 are largely orthogonal techniques, but many ways where one could be replaced with the other…and that’s where the confusion </li></ul>
  4. 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. 5. Any of them works - Contd <ul><li>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 </li></ul><ul><li>In fact the template version in the previous example yields much faster code than the virtual method equivalent </li></ul><ul><li>Much prevailing confusion about which technique to use in what situation </li></ul>
  6. 6. Runtime polymorphism <ul><li>Runtime binding between abstract type and concrete type </li></ul><ul><li>Enforces a common interface for all derived types via the base class </li></ul><ul><li>Enforces an ‘Is-A’ relationship </li></ul><ul><li>Used extensively in OO frameworks </li></ul><ul><li>Templates eating into parts of its territory </li></ul>
  7. 7. Compile time Polymorphism <ul><li>Compile time binding between abstract type and concrete type </li></ul><ul><li>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 </li></ul><ul><li>Foundation of ‘Generic programming’ or programming based on ‘Concepts’ (Eg: STL) </li></ul><ul><li>A very ‘Happening area’ in C++ right now (See TR1, Boost, C++0x...) </li></ul>
  8. 8. Why all the excitement about templates? <ul><li>Templates – </li></ul><ul><ul><li>Buy us generality in software, without the ‘Abstraction penalty’ </li></ul></ul><ul><ul><li>Are type safe </li></ul></ul><ul><ul><li>Are non-intrusive </li></ul></ul><ul><ul><li>Allow both reference and value semantics unlike virtuals </li></ul></ul>
  9. 9. Design of reusable data structures – Inheritance or Templates? Value or Reference semantics, both allowed Reference semantics only (leaks, crashes..) 4 Non-Intrusive Intrusive (put an int/char inside a class and derive from base) 3 Type safe Non type-safe (Crash!) 2 Faster Slower (virtuals) 1 Template based approach Inheritance based approach Index
  10. 10. Sure choice - Templates <ul><li>So, templates lead to ‘Faster, Safer, and Easier to reuse’ data structures than inheritance </li></ul><ul><li>Using inheritance for designing generic data structures, is a common mistake in C++ </li></ul><ul><li>Dates back to days where compiler support was bad for templates </li></ul>
  11. 11. Why inheritance then? <ul><li>Code and structure reuse from base classes </li></ul><ul><li>OO Frameworks </li></ul><ul><ul><li>Framework implementation requires ‘Heterogeneous containers’ </li></ul></ul><ul><ul><li>Reactor example </li></ul></ul><ul><ul><li>Often depend on polymorphic return types </li></ul></ul><ul><ul><li>Factory example </li></ul></ul><ul><ul><li>Can’t do that with templates </li></ul></ul>
  12. 12. Choosing your polymorphism <ul><li>Don’t overuse inheritance (Implementing data structures using inheritance is an example of misuse of inheritance) </li></ul><ul><li>Evaluate if your design could be done using templates, they are faster and safer than virtuals. </li></ul><ul><li>Read up on templates and be aware of its pitfalls (Another class of mine will deal with that) </li></ul>
  13. 13. Vanilla or Strawberry? I think I’ll have both <ul><li>Templates and Inheritance can be combined sometimes </li></ul><ul><ul><li>Eg 1: Singleton pattern implementation </li></ul></ul><ul><ul><li>Eg 2: Reusable object counter </li></ul></ul><ul><ul><li>Eg 3: Reducing template code bloat </li></ul></ul><ul><li>Weakness of inheritance – Base classes don’t know the type of their derived classes </li></ul><ul><li>Static attributes in base class are ‘Shared’ </li></ul><ul><li>Weakness of templates – They don’t lead to an ‘Is-A’ relationship </li></ul>
  14. 14. Singleton using the van-berry flavor <ul><li>Best of both worlds </li></ul><ul><ul><li>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] </li></ul></ul><ul><ul><li>Enforce ‘Is-A’ relationship using inheritance [Eg: Make ctor private in the base class, so nobody can instantiate a derived class instance as well] </li></ul></ul>
  15. 15. Object counter <ul><li>Synergy again </li></ul><ul><ul><li>Base classes need to share the static attributes </li></ul></ul><ul><ul><li>Use templates to get over that issue – One base class generated for each derived class </li></ul></ul><ul><ul><li>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] </li></ul></ul>
  16. 16. Cost of runtime polymorphism <ul><li>Each class that has a virtual method has an associated ‘vtable’ </li></ul><ul><li>A ‘vtable’ is just an array of function pointers containing pointers to virtual method implementations for that class </li></ul><ul><li>Each object of any such class, has a pointer to the associated vtable </li></ul><ul><li>The compiler creates the required vtables and initializes each object to point to the associated vtable all ‘Under the hood’ </li></ul>
  17. 17. Illustration Class Base { public: Base(); virtual void func1(); virtual void func2(); virtual ~Base(): }; Class Derived { public: Derived(); virtual void func1(); virtual ~Derived(); };
  18. 18. Illustration (Contd) vtable for the Derived class vtable for the Base class Pointer to Base::~Base Pointer to Base::func2 Pointer to Base::func1 Pointer to Derived::~Derived Pointer to Base::func2 Pointer to Derived::func1
  19. 19. Illustration (Contd)
  20. 20. What happens at runtime? <ul><li>The compiler would have converted all your virtual method calls </li></ul><ul><ul><li>Your call: pDerived->func2(); </li></ul></ul><ul><ul><li>It’s become: (*pDerived->vptr[1])(pDerived) </li></ul></ul><ul><li>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 </li></ul>
  21. 21. So, what’s the cost? <ul><li>Direct cost – vtable lookup (Put at about 5-10% overhead as opposed to non-virtual methods) </li></ul><ul><li>Indirect cost – </li></ul><ul><ul><li>Cannot inline virtual methods (Makes a big difference) </li></ul></ul><ul><ul><li>Each objects needs to store extra pointer (An issue for fine grained objects – say 1000000 link element objects, each containing 4 bytes extra!) </li></ul></ul>
  22. 22. Is that all? <ul><li>Well, this gets worse when MI (Multiple Inheritance is used) </li></ul><ul><li>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 </li></ul><ul><li>Ensure your most frequently called methods are from the FIRST base class you derive from if you use MI, order your base classes accordingly </li></ul>
  23. 23. Cost of compile time polymorphism <ul><li>ZERO runtime cost (Abstraction without abstraction penalty) </li></ul><ul><li>However … </li></ul><ul><ul><li>Coders not aware of how templates work ‘Under the hood’ end up creating code bloat </li></ul></ul><ul><ul><li>Developer turn around time increased due to longer compiles (This could be avoided too) </li></ul></ul>
  24. 24. Template code bloat <ul><li>Code bloat happens because compilers cannot do ‘Commonality and variability analysis’ </li></ul><ul><li>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 </li></ul><ul><li>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 </li></ul>
  25. 25. Template code bloat (Contd) <ul><li>A coder who knows this, does the following </li></ul><ul><ul><li>Give a partial template specialization for POINTER types </li></ul></ul><ul><ul><li>Have that derive from a void * based container which has most of the implementation in it </li></ul></ul><ul><ul><li>This specialized class will have simple inline methods that ‘Delegate’ to the base class and gets work done </li></ul></ul>
  26. 26. Template code bloat (Contd) <ul><li>So, we get the following result – </li></ul><ul><ul><li>The thin inline wrappers in the specialized class offer type safety </li></ul></ul><ul><ul><li>Majority of the code body is in the non-template base class and hence no duplication of it </li></ul></ul><ul><ul><li>The thin wrappers are all inline hence no performance overhead as well </li></ul></ul><ul><li>This is called the ‘Hoisting idiom’ </li></ul>
  27. 27. Longer compilation time <ul><li>Happens mainly because the template method definitions have to be in the header file </li></ul><ul><li>They may in turn pull in other headers and hence lead to large include sizes and hence more compile time </li></ul><ul><li>More work to the compiler in case one uses template meta-programming </li></ul>
  28. 28. Workaround <ul><li>To reduce compile times, we can use the ‘Explicit instantiation’ technique in cases where large includes are warranted </li></ul><ul><li>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 </li></ul>
  29. 29. Summary <ul><li>Prefer inheritance when </li></ul><ul><ul><li>You want to reuse code/structure from the base class </li></ul></ul><ul><ul><li>You want to develop OO frameworks which need to store heterogeneous elements in their data structures </li></ul></ul><ul><li>Prefer templates when </li></ul><ul><ul><li>You want generic data structures and algorithms </li></ul></ul><ul><ul><li>Where Speed is important </li></ul></ul>

×