SlideShare a Scribd company logo
www.luxoft.com
Volodymyr Bahrii
Understanding polymorphism in C++
www.luxoft.com
Agenda
• What is polymorphism?
• Static polymorphism
• function overloading and templates
• CRTP
• Dynamic polymorphism
• keyword virtual
• virtual method table (VMT)
• virtual destructor
• calling virtual function from a constructor (pure virtual call)
• Conclusion
www.luxoft.com
What is polymorphism?


polymorphism - providing a single interface to entities of different types. virtual functions provide
dynamic (run-time) polymorphism through an interface provided by a base class. Overloaded
functions and templates provide static (compile-time) polymorphism. TC++PL 12.2.6, 13.6.1, D&E
2.9.



— Bjarne Stroustrup's glossary (http://www.stroustrup.com/glossary.html)
www.luxoft.com
Output helper
#pragma once
#include <iostream>
#define PRINT_FUNC_NAME() std::cout << __PRETTY_FUNCTION__ << std::endl;
#define PRINT_SEPARATOR() std::cout << “====================" << std::endl;
#define PRINT_TITLE() PRINT_SEPARATOR(); 
PRINT_FUNC_NAME(); 
PRINT_SEPARATOR();
www.luxoft.com
Static polymorphism
www.luxoft.com
Function overloading and templates
output:
void func(int)
{
PRINT_FUNC_NAME();
}
void func(double)
{
PRINT_FUNC_NAME();
}
void func(bool, int)
{
PRINT_FUNC_NAME();
}
template<class T>
void func(T)
{
PRINT_FUNC_NAME();
}
int main()
{
func(1);
func(1.);
func(true, 1);
func("1");
func('1');
return 0;
}
www.luxoft.com
nm utility
nm ./a.out
The nm utility shall display symbolic information appearing in the object file, executable file, or
object-file library named by file. If no symbolic information is available for a valid input file,
the nm utility shall report that fact, but not consider it an error condition.
— http://pubs.opengroup.org/onlinepubs/9699919799/utilities/nm.html
Symbol type, which shall either be one of the following single
characters or an implementation-defined type represented by
a single character:
A - Global absolute symbol.
a - Local absolute symbol.
B - Global "bss" (that is, uninitialized data space) symbol.
b - Local bss symbol.
D - Global data symbol.
d - Local data symbol.
T - Global text symbol.
t - Local text symbol.
U - Undefined symbol.
www.luxoft.com
Function overloading and templates
c++filt
The C ++ and Java languages provide function overloading, which means that you can write many
functions with the same name, providing that each function takes parameters of different types. In
order to be able to distinguish these similarly named functions C ++ and Java encode them into a
low-level assembler name which uniquely identifies each different version. This process is known as
mangling. The c++filt [1] program does the inverse mapping: it decodes (demangles) low-level
names into user-level names so that they can be read.
— https://linux.die.net/man/1/c++filt
www.luxoft.com
Curiously recurring template pattern (CRTP)
The curiously recurring template pattern (CRTP) is an idiom in C++ in which a class X derives from a
class template instantiation using X itself as template argument.[1] More generally it is known as F-
bound polymorphism, and it is a form of F-bounded quantification.
www.luxoft.com
CRTP example
template <class DerivedClass>
struct Base
{
void interface()
{
PRINT_FUNC_NAME();
static_cast<DerivedClass*>(this)->implementation();
}
};
struct Derived : Base<Derived> 

{
void implementation() 

{
PRINT_FUNC_NAME();
}
};
struct BadDerived : Base<BadDerived> 

{
// without method implementation()
};
template<class T>
void process(Base<T>& base)
{
base.interface();
}
int main() 

{
Derived d;
process(d);
BadDerived bd;
process(bd); // Compile Error
return 0;
}
www.luxoft.com
CRTP execution
Compile error: no member
named ‘implementation’ in
‘BadDerived’
www.luxoft.com
Dynamic polymorphism
www.luxoft.com
Dynamic polymorphism
— Working Draft, Standard for Programming Language C++ (Document Number: N4659.
Date: 2017-03-21)
www.luxoft.com
Virtual table
Whenever a class defines a virtual function (or method), most compilers add a hidden member
variable to the class which points to an array of pointers to (virtual) functions called the virtual
method table (VMT or Vtable). 

— Wikipedia (https://en.wikipedia.org/wiki/Virtual_method_table)
www.luxoft.com
Where is the virtual table?
Standard for Programming Language C++ does
not specify that virtual tables are required -
however that is how most compilers implement
virtual functions.

www.luxoft.com
Record layout
struct A
{
virtual void foo() {}
};
g++ -cc1 -fdump-record-layouts show_layout.cpp
struct D : B, C 

{ 

};
struct B
{
virtual void bar() {}
};
struct C : A 

{ 

};
int main()
{
return sizeof(D);
}
www.luxoft.com
Retrieving pointer to virtual table
output:
class A
{
};
class B
{
virtual void foo()
{
}
};
struct VtablePtrHolder
{
int* vptr = nullptr;
};
int main()
{
A a;
VtablePtrHolder* holder = nullptr;
holder = reinterpret_cast<VtablePtrHolder*>(&a);
std::cout << "Vtable ptr: " << holder->vptr << std::endl;
B b;
holder = reinterpret_cast<VtablePtrHolder*>(&b);
std::cout << "Vtable ptr: " << holder->vptr << std::endl;
return 0;
}
www.luxoft.com
Indirect call of virtual function
struct Base
{
virtual void foo()
{
PRINT_FUNC_NAME();
}
};
struct Base2
{
virtual int bar(int)
{
PRINT_FUNC_NAME();
return 0;
}
virtual void tmp()
{
PRINT_FUNC_NAME();
}
};
struct Derived : Base, Base2
{
void foo() override
{
PRINT_FUNC_NAME();
}
int bar(int) override
{
PRINT_FUNC_NAME();
return 1;
}
void tmp() override
{
PRINT_FUNC_NAME();
}
};
struct VtablePtrHolder
{
int* vtable1_ptr = nullptr;
int* vtable2_ptr = nullptr;
};
www.luxoft.com
Indirect call of virtual function
int main()
{
Derived d;
VtablePtrHolder* holder = reinterpret_cast<VtablePtrHolder*>(&d);
output:
typedef void (*functionType)();
functionType* virtual_foo = (functionType*)(holder->vtable1_ptr);
(*virtual_foo)();
typedef int (*barFuncType)(int);
barFuncType* virtual_bar = (barFuncType*)(holder->vtable2_ptr);
(*virtual_bar)(5);
int* ptr = holder->vtable2_ptr;
ptr += sizeof(int*) / sizeof(int); // 2 for x64, 1 for x32
functionType* virtual_tmp = (functionType*)(ptr);
(*virtual_tmp)();
return 0;
}
www.luxoft.com
Virtual destructor
• Destructors in the Base class can be Virtual.
Whenever Upcasting is done, Destructors of the
Base class must be made virtual for proper
destruction of the object when the program exits.
• Pure Virtual Destructors are legal in C++. Also,
pure virtual Destructors must be defined, which is
against the pure virtual behaviour.
• The only difference between Virtual and Pure Virtual
Destructor is, that pure virtual destructor will make its
Base class Abstract, hence you cannot create object
of that class.
www.luxoft.com
Virtual destructor vs non-virtual destructor
struct Derived : Base
{
std::unique_ptr<Test> ptr;
Derived()
{
PRINT_FUNC_NAME();
ptr.reset(new Test);
}
~Derived()
{
PRINT_FUNC_NAME();
}
};
int main()
{
Base* base = new Derived;
delete base;
return 0;
}
output (non-virtual)
output (virtual destructor)
struct Base
{
Base() {
PRINT_FUNC_NAME();
}
/*virtual*/ ~Base() {
PRINT_FUNC_NAME();
}
};
struct Test final{
Test() {
PRINT_FUNC_NAME();
}
~Test() {
PRINT_FUNC_NAME();
}
www.luxoft.com
Memory leak
In computer science, a memory leak is a type of resource leak that occurs when a computer
program incorrectly manages memory allocations in such a way that memory which is no longer
needed is not released. In object-oriented programming, a memory leak may happen when an
object is stored in memory but cannot be accessed by the running code. A memory leak has
symptoms similar to a number of other problems and generally can only be diagnosed by a
programmer with access to the program's source code.
www.luxoft.com
Invoking virtual method in a constructor
A virtual function can be invoked in a constructor, but be careful. It may not do what you expect. In a
constructor, the virtual call mechanism is disabled because overriding from derived classes hasn’t
yet happened. Objects are constructed from the base up, “base before derived”.
www.luxoft.com
Pure virtual function call
struct Base
{
Base()
{
foo(); // invoking virtual function
}
virtual ~Base()
{
}
virtual void foo() = 0;
};
struct Derived : Base
{
void foo() override
{
// do something important
}
};
int main()
{
Base* base = new Derived;
delete base;
return 0;
}
www.luxoft.com
Conclusion
• use CRTP to avoid dynamic dispatching
• make destructors virtual in base classes
• use keywords override and final (C++11/14/17)
• do not invoke virtual functions on constructor/destructor
www.luxoft.com
Thank you

More Related Content

PPTX
Summary of C++17 features
PDF
C++20 the small things - Timur Doumler
PDF
Modern c++ (C++ 11/14)
PDF
Le langage rust
PDF
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
ODP
OOP in C - Before GObject (Chinese Version)
PDF
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
PDF
C++11 concurrency
Summary of C++17 features
C++20 the small things - Timur Doumler
Modern c++ (C++ 11/14)
Le langage rust
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
OOP in C - Before GObject (Chinese Version)
개발 과정 최적화 하기 내부툴로 더욱 강력한 개발하기 Stephen kennedy _(11시40분_103호)
C++11 concurrency

What's hot (20)

PDF
C++11: Rvalue References, Move Semantics, Perfect Forwarding
PDF
OOP in C - Inherit (Chinese Version)
PPT
What's New in C++ 11?
ODP
OpenGurukul : Language : C++ Programming
PPTX
Let's talks about string operations in C++17
PDF
С++ without new and delete
PDF
Антон Бикинеев, Reflection in C++Next
PPTX
C++ Presentation
PPTX
C++17 std::filesystem - Overview
PPT
Constructor,destructors cpp
PPTX
Vocabulary Types in C++17
PPTX
Дмитрий Нестерук, Паттерны проектирования в XXI веке
PPTX
Fun with Lambdas: C++14 Style (part 2)
PDF
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
PPTX
Алексей Кутумов, Вектор с нуля
PDF
Smart Pointers in C++
PPTX
Operator overloading2
PDF
C++aptitude questions and answers
PDF
C++ references
PDF
C# / Java Language Comparison
C++11: Rvalue References, Move Semantics, Perfect Forwarding
OOP in C - Inherit (Chinese Version)
What's New in C++ 11?
OpenGurukul : Language : C++ Programming
Let's talks about string operations in C++17
С++ without new and delete
Антон Бикинеев, Reflection in C++Next
C++ Presentation
C++17 std::filesystem - Overview
Constructor,destructors cpp
Vocabulary Types in C++17
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Fun with Lambdas: C++14 Style (part 2)
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
Алексей Кутумов, Вектор с нуля
Smart Pointers in C++
Operator overloading2
C++aptitude questions and answers
C++ references
C# / Java Language Comparison
Ad

Similar to Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17 (20)

PPTX
ppl unit 3.pptx ppl unit 3 usefull can understood
PPT
Virtual Function and Polymorphism.ppt
PDF
JVM Mechanics: When Does the JVM JIT & Deoptimize?
PPTX
Cross Platform App Development with C++
PDF
Silicon Valley JUG: JVM Mechanics
PPTX
C++11: Feel the New Language
PDF
polymorphism for b.tech iii year students
PDF
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
PDF
Kotlin Developer Starter in Android projects
PDF
Object Oriented Programming (OOP) using C++ - Lecture 4
PDF
C++ aptitude
PDF
PHP 8: Process & Fixing Insanity
PPT
presentation_functions_1443207686_140676.ppt
PPT
C programming is a powerful, general-purpose language used for developing ope...
PPTX
constructors shailee.pptxhhhtyygdxixixxxxix
PPTX
Boost.Python: C++ and Python Integration
PDF
Scala is java8.next()
DOCX
C questions
PPTX
C++ idioms.pptx
PPTX
Iron Languages - NYC CodeCamp 2/19/2011
ppl unit 3.pptx ppl unit 3 usefull can understood
Virtual Function and Polymorphism.ppt
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Cross Platform App Development with C++
Silicon Valley JUG: JVM Mechanics
C++11: Feel the New Language
polymorphism for b.tech iii year students
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android projects
Object Oriented Programming (OOP) using C++ - Lecture 4
C++ aptitude
PHP 8: Process & Fixing Insanity
presentation_functions_1443207686_140676.ppt
C programming is a powerful, general-purpose language used for developing ope...
constructors shailee.pptxhhhtyygdxixixxxxix
Boost.Python: C++ and Python Integration
Scala is java8.next()
C questions
C++ idioms.pptx
Iron Languages - NYC CodeCamp 2/19/2011
Ad

More from LogeekNightUkraine (20)

PPTX
Face recognition with c++
PPTX
C++20 features
PPTX
Autonomous driving on your developer pc. technologies, approaches, future
PDF
Orkhan Gasimov "High Performance System Design"
PPTX
Vitalii Korzh "Managed Workflows or How to Master Data"
PDF
Yevhen Tatarynov "From POC to High-Performance .NET applications"
PDF
Oleksii Kuchuk "Reading gauge values with open cv imgproc"
PDF
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
PDF
Pavlo Zhdanov "Mastering solid and base principles for software design"
PDF
Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"
PDF
Iurii Antykhovych "Java and performance tools and toys"
PDF
Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...
PPTX
Aleksandr Kutsan "Managing Dependencies in C++"
PDF
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
PDF
Alexandr Golyak, Nikolay Chertkov "Automotive Testing vs Test Automatio"
PPTX
Michal Kordas "Docker: Good, Bad or Both"
PPTX
Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"
PPTX
Shestakov Illia "The Sandbox Theory"
PPTX
Dmytro Kochergin “Autotest with CYPRESS”
PPTX
Ivan Dryzhyruk “Ducks Don’t Like Bugs”
Face recognition with c++
C++20 features
Autonomous driving on your developer pc. technologies, approaches, future
Orkhan Gasimov "High Performance System Design"
Vitalii Korzh "Managed Workflows or How to Master Data"
Yevhen Tatarynov "From POC to High-Performance .NET applications"
Oleksii Kuchuk "Reading gauge values with open cv imgproc"
Oleksandr Kutsan "Using katai struct to describe the process of working with ...
Pavlo Zhdanov "Mastering solid and base principles for software design"
Serhii Zemlianyi "Error Retries with Exponential Backoff Using RabbitMQ"
Iurii Antykhovych "Java and performance tools and toys"
Eugene Bova "Dapr (Distributed Application Runtime) in a Microservices Archit...
Aleksandr Kutsan "Managing Dependencies in C++"
Yevhen Tatarynov "My .NET Application Allocates too Much Memory. What Can I Do?"
Alexandr Golyak, Nikolay Chertkov "Automotive Testing vs Test Automatio"
Michal Kordas "Docker: Good, Bad or Both"
Kolomiyets Dmytro "Dealing with Multiple Caches, When Developing Microservices"
Shestakov Illia "The Sandbox Theory"
Dmytro Kochergin “Autotest with CYPRESS”
Ivan Dryzhyruk “Ducks Don’t Like Bugs”

Recently uploaded (20)

PPTX
Lecture 3b C Library xnxjxjxjxkx_ ESP32.pptx
PPTX
deforestation.ppt[1]bestpptondeforestation.pptx
DOCX
lp of food hygiene.docxvvvvvvvvvvvvvvvvvvvvvvv
PDF
How Much does a Volvo EC290C NL EC290CNL Weight.pdf
PPTX
Independence_Day_Patriotic theme (1).pptx
PDF
EC290C NL EC290CNL Volvo excavator specs.pdf
PPTX
building_blocks.pptxdcsDVabdbzfbtydtyyjtj67
PDF
book-slidefsdljflsk fdslkfjslf sflgs.pdf
PPTX
Intro to ISO 9001 2015.pptx for awareness
PPTX
UNIT-2(B) Organisavtional Appraisal.pptx
PPTX
Business Economics uni 1.pptxRTRETRETRTRETRETRETRETERT
PDF
RPL-ASDC PPT PROGRAM NSDC GOVT SKILLS INDIA
PPTX
Advance Module FI 160.pptx para pulsaar 160 y su sistema de encencido
PPTX
Robot_ppt_YRG[1] [Read-Only]bestppt.pptx
PPTX
Small Fleets, Big Change: Market Acceleration by Niki Okuk
PDF
Lubrication system for Automotive technologies
PPTX
368455847-Relibility RJS-Relibility-PPT-1.pptx
PPTX
Culture by Design.pptxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
PPTX
Understanding Machine Learning with artificial intelligence.pptx
PDF
Volvo EC20C Excavator Service maintenance schedules.pdf
Lecture 3b C Library xnxjxjxjxkx_ ESP32.pptx
deforestation.ppt[1]bestpptondeforestation.pptx
lp of food hygiene.docxvvvvvvvvvvvvvvvvvvvvvvv
How Much does a Volvo EC290C NL EC290CNL Weight.pdf
Independence_Day_Patriotic theme (1).pptx
EC290C NL EC290CNL Volvo excavator specs.pdf
building_blocks.pptxdcsDVabdbzfbtydtyyjtj67
book-slidefsdljflsk fdslkfjslf sflgs.pdf
Intro to ISO 9001 2015.pptx for awareness
UNIT-2(B) Organisavtional Appraisal.pptx
Business Economics uni 1.pptxRTRETRETRTRETRETRETRETERT
RPL-ASDC PPT PROGRAM NSDC GOVT SKILLS INDIA
Advance Module FI 160.pptx para pulsaar 160 y su sistema de encencido
Robot_ppt_YRG[1] [Read-Only]bestppt.pptx
Small Fleets, Big Change: Market Acceleration by Niki Okuk
Lubrication system for Automotive technologies
368455847-Relibility RJS-Relibility-PPT-1.pptx
Culture by Design.pptxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Understanding Machine Learning with artificial intelligence.pptx
Volvo EC20C Excavator Service maintenance schedules.pdf

Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17

  • 2. www.luxoft.com Agenda • What is polymorphism? • Static polymorphism • function overloading and templates • CRTP • Dynamic polymorphism • keyword virtual • virtual method table (VMT) • virtual destructor • calling virtual function from a constructor (pure virtual call) • Conclusion
  • 3. www.luxoft.com What is polymorphism? 
 polymorphism - providing a single interface to entities of different types. virtual functions provide dynamic (run-time) polymorphism through an interface provided by a base class. Overloaded functions and templates provide static (compile-time) polymorphism. TC++PL 12.2.6, 13.6.1, D&E 2.9.
 
 — Bjarne Stroustrup's glossary (http://www.stroustrup.com/glossary.html)
  • 4. www.luxoft.com Output helper #pragma once #include <iostream> #define PRINT_FUNC_NAME() std::cout << __PRETTY_FUNCTION__ << std::endl; #define PRINT_SEPARATOR() std::cout << “====================" << std::endl; #define PRINT_TITLE() PRINT_SEPARATOR(); PRINT_FUNC_NAME(); PRINT_SEPARATOR();
  • 6. www.luxoft.com Function overloading and templates output: void func(int) { PRINT_FUNC_NAME(); } void func(double) { PRINT_FUNC_NAME(); } void func(bool, int) { PRINT_FUNC_NAME(); } template<class T> void func(T) { PRINT_FUNC_NAME(); } int main() { func(1); func(1.); func(true, 1); func("1"); func('1'); return 0; }
  • 7. www.luxoft.com nm utility nm ./a.out The nm utility shall display symbolic information appearing in the object file, executable file, or object-file library named by file. If no symbolic information is available for a valid input file, the nm utility shall report that fact, but not consider it an error condition. — http://pubs.opengroup.org/onlinepubs/9699919799/utilities/nm.html Symbol type, which shall either be one of the following single characters or an implementation-defined type represented by a single character: A - Global absolute symbol. a - Local absolute symbol. B - Global "bss" (that is, uninitialized data space) symbol. b - Local bss symbol. D - Global data symbol. d - Local data symbol. T - Global text symbol. t - Local text symbol. U - Undefined symbol.
  • 8. www.luxoft.com Function overloading and templates c++filt The C ++ and Java languages provide function overloading, which means that you can write many functions with the same name, providing that each function takes parameters of different types. In order to be able to distinguish these similarly named functions C ++ and Java encode them into a low-level assembler name which uniquely identifies each different version. This process is known as mangling. The c++filt [1] program does the inverse mapping: it decodes (demangles) low-level names into user-level names so that they can be read. — https://linux.die.net/man/1/c++filt
  • 9. www.luxoft.com Curiously recurring template pattern (CRTP) The curiously recurring template pattern (CRTP) is an idiom in C++ in which a class X derives from a class template instantiation using X itself as template argument.[1] More generally it is known as F- bound polymorphism, and it is a form of F-bounded quantification.
  • 10. www.luxoft.com CRTP example template <class DerivedClass> struct Base { void interface() { PRINT_FUNC_NAME(); static_cast<DerivedClass*>(this)->implementation(); } }; struct Derived : Base<Derived> 
 { void implementation() 
 { PRINT_FUNC_NAME(); } }; struct BadDerived : Base<BadDerived> 
 { // without method implementation() }; template<class T> void process(Base<T>& base) { base.interface(); } int main() 
 { Derived d; process(d); BadDerived bd; process(bd); // Compile Error return 0; }
  • 11. www.luxoft.com CRTP execution Compile error: no member named ‘implementation’ in ‘BadDerived’
  • 13. www.luxoft.com Dynamic polymorphism — Working Draft, Standard for Programming Language C++ (Document Number: N4659. Date: 2017-03-21)
  • 14. www.luxoft.com Virtual table Whenever a class defines a virtual function (or method), most compilers add a hidden member variable to the class which points to an array of pointers to (virtual) functions called the virtual method table (VMT or Vtable). 
 — Wikipedia (https://en.wikipedia.org/wiki/Virtual_method_table)
  • 15. www.luxoft.com Where is the virtual table? Standard for Programming Language C++ does not specify that virtual tables are required - however that is how most compilers implement virtual functions.

  • 16. www.luxoft.com Record layout struct A { virtual void foo() {} }; g++ -cc1 -fdump-record-layouts show_layout.cpp struct D : B, C 
 { 
 }; struct B { virtual void bar() {} }; struct C : A 
 { 
 }; int main() { return sizeof(D); }
  • 17. www.luxoft.com Retrieving pointer to virtual table output: class A { }; class B { virtual void foo() { } }; struct VtablePtrHolder { int* vptr = nullptr; }; int main() { A a; VtablePtrHolder* holder = nullptr; holder = reinterpret_cast<VtablePtrHolder*>(&a); std::cout << "Vtable ptr: " << holder->vptr << std::endl; B b; holder = reinterpret_cast<VtablePtrHolder*>(&b); std::cout << "Vtable ptr: " << holder->vptr << std::endl; return 0; }
  • 18. www.luxoft.com Indirect call of virtual function struct Base { virtual void foo() { PRINT_FUNC_NAME(); } }; struct Base2 { virtual int bar(int) { PRINT_FUNC_NAME(); return 0; } virtual void tmp() { PRINT_FUNC_NAME(); } }; struct Derived : Base, Base2 { void foo() override { PRINT_FUNC_NAME(); } int bar(int) override { PRINT_FUNC_NAME(); return 1; } void tmp() override { PRINT_FUNC_NAME(); } }; struct VtablePtrHolder { int* vtable1_ptr = nullptr; int* vtable2_ptr = nullptr; };
  • 19. www.luxoft.com Indirect call of virtual function int main() { Derived d; VtablePtrHolder* holder = reinterpret_cast<VtablePtrHolder*>(&d); output: typedef void (*functionType)(); functionType* virtual_foo = (functionType*)(holder->vtable1_ptr); (*virtual_foo)(); typedef int (*barFuncType)(int); barFuncType* virtual_bar = (barFuncType*)(holder->vtable2_ptr); (*virtual_bar)(5); int* ptr = holder->vtable2_ptr; ptr += sizeof(int*) / sizeof(int); // 2 for x64, 1 for x32 functionType* virtual_tmp = (functionType*)(ptr); (*virtual_tmp)(); return 0; }
  • 20. www.luxoft.com Virtual destructor • Destructors in the Base class can be Virtual. Whenever Upcasting is done, Destructors of the Base class must be made virtual for proper destruction of the object when the program exits. • Pure Virtual Destructors are legal in C++. Also, pure virtual Destructors must be defined, which is against the pure virtual behaviour. • The only difference between Virtual and Pure Virtual Destructor is, that pure virtual destructor will make its Base class Abstract, hence you cannot create object of that class.
  • 21. www.luxoft.com Virtual destructor vs non-virtual destructor struct Derived : Base { std::unique_ptr<Test> ptr; Derived() { PRINT_FUNC_NAME(); ptr.reset(new Test); } ~Derived() { PRINT_FUNC_NAME(); } }; int main() { Base* base = new Derived; delete base; return 0; } output (non-virtual) output (virtual destructor) struct Base { Base() { PRINT_FUNC_NAME(); } /*virtual*/ ~Base() { PRINT_FUNC_NAME(); } }; struct Test final{ Test() { PRINT_FUNC_NAME(); } ~Test() { PRINT_FUNC_NAME(); }
  • 22. www.luxoft.com Memory leak In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. In object-oriented programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code. A memory leak has symptoms similar to a number of other problems and generally can only be diagnosed by a programmer with access to the program's source code.
  • 23. www.luxoft.com Invoking virtual method in a constructor A virtual function can be invoked in a constructor, but be careful. It may not do what you expect. In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn’t yet happened. Objects are constructed from the base up, “base before derived”.
  • 24. www.luxoft.com Pure virtual function call struct Base { Base() { foo(); // invoking virtual function } virtual ~Base() { } virtual void foo() = 0; }; struct Derived : Base { void foo() override { // do something important } }; int main() { Base* base = new Derived; delete base; return 0; }
  • 25. www.luxoft.com Conclusion • use CRTP to avoid dynamic dispatching • make destructors virtual in base classes • use keywords override and final (C++11/14/17) • do not invoke virtual functions on constructor/destructor