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

What's hot

C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect Forwarding
Francesco Casalegno
 
OOP in C - Inherit (Chinese Version)
OOP in C - Inherit (Chinese Version)OOP in C - Inherit (Chinese Version)
OOP in C - Inherit (Chinese Version)Kai-Feng Chou
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
Sasha Goldshtein
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
Open Gurukul
 
Let's talks about string operations in C++17
Let's talks about string operations in C++17Let's talks about string operations in C++17
Let's talks about string operations in C++17
Bartlomiej Filipek
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and delete
Platonov Sergey
 
Антон Бикинеев, Reflection in C++Next
Антон Бикинеев,  Reflection in C++NextАнтон Бикинеев,  Reflection in C++Next
Антон Бикинеев, Reflection in C++Next
Sergey Platonov
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
Carson Wilber
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - Overview
Bartlomiej Filipek
 
Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
Bartlomiej Filipek
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI векеДмитрий Нестерук, Паттерны проектирования в XXI веке
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Sergey Platonov
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
Chris Ohk
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
Sergey Platonov
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
Francesco Casalegno
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
zindadili
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
sheibansari
 
C++ references
C++ referencesC++ references
C++ references
corehard_by
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language Comparison
Robert Bachmann
 

What's hot (20)

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

Similar to Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17

Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
ishan743441
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Doug Hawkins
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++
Joan Puig Sanz
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Languagemspline
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
GeorgePeterBanyard
 
presentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.pptpresentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.ppt
SandipPradhan23
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python Integration
GlobalLogic Ukraine
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 
C questions
C questionsC questions
C questions
parm112
 
C++ idioms.pptx
C++ idioms.pptxC++ idioms.pptx
C++ idioms.pptx
Janani Anbarasan
 
Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011
Jimmy Schementi
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
ppd1961
 
Swift core
Swift coreSwift core
Swift core
Yusuke Kita
 

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

Virtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.pptVirtual Function and Polymorphism.ppt
Virtual Function and Polymorphism.ppt
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Cross Platform App Development with C++
Cross Platform App Development with C++Cross Platform App Development with C++
Cross Platform App Development with C++
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
presentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.pptpresentation_functions_1443207686_140676.ppt
presentation_functions_1443207686_140676.ppt
 
Boost.Python: C++ and Python Integration
Boost.Python: C++ and Python IntegrationBoost.Python: C++ and Python Integration
Boost.Python: C++ and Python Integration
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
C questions
C questionsC questions
C questions
 
C++ idioms.pptx
C++ idioms.pptxC++ idioms.pptx
C++ idioms.pptx
 
Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011Iron Languages - NYC CodeCamp 2/19/2011
Iron Languages - NYC CodeCamp 2/19/2011
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
Swift core
Swift coreSwift core
Swift core
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Day 1
Day 1Day 1
Day 1
 

More from LogeekNightUkraine

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

More from LogeekNightUkraine (20)

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

Recently uploaded

What Are The Immediate Steps To Take When The VW Temperature Light Starts Fla...
What Are The Immediate Steps To Take When The VW Temperature Light Starts Fla...What Are The Immediate Steps To Take When The VW Temperature Light Starts Fla...
What Are The Immediate Steps To Take When The VW Temperature Light Starts Fla...
Import Motorworks
 
Antique Plastic Traders Company Profile
Antique Plastic Traders Company ProfileAntique Plastic Traders Company Profile
Antique Plastic Traders Company Profile
Antique Plastic Traders
 
Why Is Your BMW X3 Hood Not Responding To Release Commands
Why Is Your BMW X3 Hood Not Responding To Release CommandsWhy Is Your BMW X3 Hood Not Responding To Release Commands
Why Is Your BMW X3 Hood Not Responding To Release Commands
Dart Auto
 
What Does the PARKTRONIC Inoperative, See Owner's Manual Message Mean for You...
What Does the PARKTRONIC Inoperative, See Owner's Manual Message Mean for You...What Does the PARKTRONIC Inoperative, See Owner's Manual Message Mean for You...
What Does the PARKTRONIC Inoperative, See Owner's Manual Message Mean for You...
Autohaus Service and Sales
 
What Causes 'Trans Failsafe Prog' to Trigger in BMW X5
What Causes 'Trans Failsafe Prog' to Trigger in BMW X5What Causes 'Trans Failsafe Prog' to Trigger in BMW X5
What Causes 'Trans Failsafe Prog' to Trigger in BMW X5
European Service Center
 
一比一原版(OP毕业证)奥塔哥理工学院毕业证成绩单如何办理
一比一原版(OP毕业证)奥塔哥理工学院毕业证成绩单如何办理一比一原版(OP毕业证)奥塔哥理工学院毕业证成绩单如何办理
一比一原版(OP毕业证)奥塔哥理工学院毕业证成绩单如何办理
mymwpc
 
一比一原版(UNITEC毕业证)UNITEC理工学院毕业证成绩单如何办理
一比一原版(UNITEC毕业证)UNITEC理工学院毕业证成绩单如何办理一比一原版(UNITEC毕业证)UNITEC理工学院毕业证成绩单如何办理
一比一原版(UNITEC毕业证)UNITEC理工学院毕业证成绩单如何办理
bouvoy
 
Hero Glamour Xtec Brochure | Hero MotoCorp
Hero Glamour Xtec Brochure | Hero MotoCorpHero Glamour Xtec Brochure | Hero MotoCorp
Hero Glamour Xtec Brochure | Hero MotoCorp
Hero MotoCorp
 
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.docBài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc
daothibichhang1
 
TRAINEES-RECORD-BOOK- electronics and electrical
TRAINEES-RECORD-BOOK- electronics and electricalTRAINEES-RECORD-BOOK- electronics and electrical
TRAINEES-RECORD-BOOK- electronics and electrical
JohnCarloPajarilloKa
 
What do the symbols on vehicle dashboard mean?
What do the symbols on vehicle dashboard mean?What do the symbols on vehicle dashboard mean?
What do the symbols on vehicle dashboard mean?
Hyundai Motor Group
 
What Could Cause The Headlights On Your Porsche 911 To Stop Working
What Could Cause The Headlights On Your Porsche 911 To Stop WorkingWhat Could Cause The Headlights On Your Porsche 911 To Stop Working
What Could Cause The Headlights On Your Porsche 911 To Stop Working
Lancer Service
 
Things to remember while upgrading the brakes of your car
Things to remember while upgrading the brakes of your carThings to remember while upgrading the brakes of your car
Things to remember while upgrading the brakes of your car
jennifermiller8137
 
Renal elimination.pdf fffffffffffffffffffff
Renal elimination.pdf fffffffffffffffffffffRenal elimination.pdf fffffffffffffffffffff
Renal elimination.pdf fffffffffffffffffffff
RehanRustam2
 
5 Red Flags Your VW Camshaft Position Sensor Might Be Failing
5 Red Flags Your VW Camshaft Position Sensor Might Be Failing5 Red Flags Your VW Camshaft Position Sensor Might Be Failing
5 Red Flags Your VW Camshaft Position Sensor Might Be Failing
Fifth Gear Automotive Cross Roads
 
5 Warning Signs Your Mercedes Exhaust Back Pressure Sensor Is Failing
5 Warning Signs Your Mercedes Exhaust Back Pressure Sensor Is Failing5 Warning Signs Your Mercedes Exhaust Back Pressure Sensor Is Failing
5 Warning Signs Your Mercedes Exhaust Back Pressure Sensor Is Failing
Fifth Gear Automotive Argyle
 
Digital Fleet Management - Why Your Business Need It?
Digital Fleet Management - Why Your Business Need It?Digital Fleet Management - Why Your Business Need It?
Digital Fleet Management - Why Your Business Need It?
jennifermiller8137
 
Statistics5,c.xz,c.;c.;d.c;d;ssssss.pptx
Statistics5,c.xz,c.;c.;d.c;d;ssssss.pptxStatistics5,c.xz,c.;c.;d.c;d;ssssss.pptx
Statistics5,c.xz,c.;c.;d.c;d;ssssss.pptx
coc7987515756
 
Why Isn't Your BMW X5's Comfort Access Functioning Properly Find Out Here
Why Isn't Your BMW X5's Comfort Access Functioning Properly Find Out HereWhy Isn't Your BMW X5's Comfort Access Functioning Properly Find Out Here
Why Isn't Your BMW X5's Comfort Access Functioning Properly Find Out Here
Masters European & Gapanese Auto Repair
 
一比一原版(AIS毕业证)奥克兰商学院毕业证成绩单如何办理
一比一原版(AIS毕业证)奥克兰商学院毕业证成绩单如何办理一比一原版(AIS毕业证)奥克兰商学院毕业证成绩单如何办理
一比一原版(AIS毕业证)奥克兰商学院毕业证成绩单如何办理
eygkup
 

Recently uploaded (20)

What Are The Immediate Steps To Take When The VW Temperature Light Starts Fla...
What Are The Immediate Steps To Take When The VW Temperature Light Starts Fla...What Are The Immediate Steps To Take When The VW Temperature Light Starts Fla...
What Are The Immediate Steps To Take When The VW Temperature Light Starts Fla...
 
Antique Plastic Traders Company Profile
Antique Plastic Traders Company ProfileAntique Plastic Traders Company Profile
Antique Plastic Traders Company Profile
 
Why Is Your BMW X3 Hood Not Responding To Release Commands
Why Is Your BMW X3 Hood Not Responding To Release CommandsWhy Is Your BMW X3 Hood Not Responding To Release Commands
Why Is Your BMW X3 Hood Not Responding To Release Commands
 
What Does the PARKTRONIC Inoperative, See Owner's Manual Message Mean for You...
What Does the PARKTRONIC Inoperative, See Owner's Manual Message Mean for You...What Does the PARKTRONIC Inoperative, See Owner's Manual Message Mean for You...
What Does the PARKTRONIC Inoperative, See Owner's Manual Message Mean for You...
 
What Causes 'Trans Failsafe Prog' to Trigger in BMW X5
What Causes 'Trans Failsafe Prog' to Trigger in BMW X5What Causes 'Trans Failsafe Prog' to Trigger in BMW X5
What Causes 'Trans Failsafe Prog' to Trigger in BMW X5
 
一比一原版(OP毕业证)奥塔哥理工学院毕业证成绩单如何办理
一比一原版(OP毕业证)奥塔哥理工学院毕业证成绩单如何办理一比一原版(OP毕业证)奥塔哥理工学院毕业证成绩单如何办理
一比一原版(OP毕业证)奥塔哥理工学院毕业证成绩单如何办理
 
一比一原版(UNITEC毕业证)UNITEC理工学院毕业证成绩单如何办理
一比一原版(UNITEC毕业证)UNITEC理工学院毕业证成绩单如何办理一比一原版(UNITEC毕业证)UNITEC理工学院毕业证成绩单如何办理
一比一原版(UNITEC毕业证)UNITEC理工学院毕业证成绩单如何办理
 
Hero Glamour Xtec Brochure | Hero MotoCorp
Hero Glamour Xtec Brochure | Hero MotoCorpHero Glamour Xtec Brochure | Hero MotoCorp
Hero Glamour Xtec Brochure | Hero MotoCorp
 
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.docBài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc
Bài tập - Tiếng anh 11 Global Success UNIT 1 - Bản HS.doc
 
TRAINEES-RECORD-BOOK- electronics and electrical
TRAINEES-RECORD-BOOK- electronics and electricalTRAINEES-RECORD-BOOK- electronics and electrical
TRAINEES-RECORD-BOOK- electronics and electrical
 
What do the symbols on vehicle dashboard mean?
What do the symbols on vehicle dashboard mean?What do the symbols on vehicle dashboard mean?
What do the symbols on vehicle dashboard mean?
 
What Could Cause The Headlights On Your Porsche 911 To Stop Working
What Could Cause The Headlights On Your Porsche 911 To Stop WorkingWhat Could Cause The Headlights On Your Porsche 911 To Stop Working
What Could Cause The Headlights On Your Porsche 911 To Stop Working
 
Things to remember while upgrading the brakes of your car
Things to remember while upgrading the brakes of your carThings to remember while upgrading the brakes of your car
Things to remember while upgrading the brakes of your car
 
Renal elimination.pdf fffffffffffffffffffff
Renal elimination.pdf fffffffffffffffffffffRenal elimination.pdf fffffffffffffffffffff
Renal elimination.pdf fffffffffffffffffffff
 
5 Red Flags Your VW Camshaft Position Sensor Might Be Failing
5 Red Flags Your VW Camshaft Position Sensor Might Be Failing5 Red Flags Your VW Camshaft Position Sensor Might Be Failing
5 Red Flags Your VW Camshaft Position Sensor Might Be Failing
 
5 Warning Signs Your Mercedes Exhaust Back Pressure Sensor Is Failing
5 Warning Signs Your Mercedes Exhaust Back Pressure Sensor Is Failing5 Warning Signs Your Mercedes Exhaust Back Pressure Sensor Is Failing
5 Warning Signs Your Mercedes Exhaust Back Pressure Sensor Is Failing
 
Digital Fleet Management - Why Your Business Need It?
Digital Fleet Management - Why Your Business Need It?Digital Fleet Management - Why Your Business Need It?
Digital Fleet Management - Why Your Business Need It?
 
Statistics5,c.xz,c.;c.;d.c;d;ssssss.pptx
Statistics5,c.xz,c.;c.;d.c;d;ssssss.pptxStatistics5,c.xz,c.;c.;d.c;d;ssssss.pptx
Statistics5,c.xz,c.;c.;d.c;d;ssssss.pptx
 
Why Isn't Your BMW X5's Comfort Access Functioning Properly Find Out Here
Why Isn't Your BMW X5's Comfort Access Functioning Properly Find Out HereWhy Isn't Your BMW X5's Comfort Access Functioning Properly Find Out Here
Why Isn't Your BMW X5's Comfort Access Functioning Properly Find Out Here
 
一比一原版(AIS毕业证)奥克兰商学院毕业证成绩单如何办理
一比一原版(AIS毕业证)奥克兰商学院毕业证成绩单如何办理一比一原版(AIS毕业证)奥克兰商学院毕业证成绩单如何办理
一比一原版(AIS毕业证)奥克兰商学院毕业证成绩单如何办理
 

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