The document discusses polymorphism in C++, including static polymorphism through function overloading and templates, and dynamic polymorphism using virtual functions and inheritance. It explains key concepts like the virtual method table that allows dynamic dispatch at runtime. The document provides examples of polymorphism techniques like the curiously recurring template pattern and proper use of virtual destructors. It warns against invoking virtual functions from constructors due to the class hierarchy not being fully established yet.
The presentation shows major features of the new C++ standard (language and the library). The full list of new things is very broad, so I've categorized them to be easier to understand.
C++20 comes with some big new language features: modules, coroutines, concepts, spaceship, and many new libraries. But apart from all those, C++20 also offers many small language improvements, making C++ more powerful and expressive, but also safer and more consistent. This talk is an overview over all those smaller additions to the core language that will make your life easier. We will discuss much-needed improvements to existing facilities such as lambdas, CTAD, structured bindings, and initialisation, as well as brand-new language utilities that you may not yet have heard about!
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
••• Exploit the full potential of the CRTP! •••
In this presentation you will learn:
▸ what is the curiously recurring template pattern
▸ the actual cost (memory and time) of virtual functions
▸ how to implement static polymorphism
▸ how to implement expression templates to avoid loops and copies
The presentation shows major features of the new C++ standard (language and the library). The full list of new things is very broad, so I've categorized them to be easier to understand.
C++20 comes with some big new language features: modules, coroutines, concepts, spaceship, and many new libraries. But apart from all those, C++20 also offers many small language improvements, making C++ more powerful and expressive, but also safer and more consistent. This talk is an overview over all those smaller additions to the core language that will make your life easier. We will discuss much-needed improvements to existing facilities such as lambdas, CTAD, structured bindings, and initialisation, as well as brand-new language utilities that you may not yet have heard about!
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
••• Exploit the full potential of the CRTP! •••
In this presentation you will learn:
▸ what is the curiously recurring template pattern
▸ the actual cost (memory and time) of virtual functions
▸ how to implement static polymorphism
▸ how to implement expression templates to avoid loops and copies
••• Boost your code's performances using C++11 new features! •••
In this presentation you will learn:
▸ the difference between an Lvalue and Rvalue
▸ how to use std::move, std::forward, noexcept
▸ how to implement move semantics to avoid useless copies
▸ how to implement perfect forwarding for the factory pattern
Со времён С++98 стандартные контейнеры и идиома RAII позволяли избегать использования оператора delete,
что делало код более безопасным. С приходом С++11 и умных указателей отпала необходимость использовать оператор new, что позволило практически полностью переложить управление памятью на плечи компилятора. В
докладе объясняется идеология управления памятью и ресурсами в современном С++.
На протяжении всего существования C++ тема компайл-тайм рефлексии поднимается постоянно, но, к сожалению, до сих пор Стандарт языка не дает достаточных возможностей для извлечения и манипулирования компайл-тайм информацией. Большое количество библиотек и препроцессоров было придумано для того, чтобы решить эту проблему, начиная от простых макросов и заканчивая Qt-moc или ODB. В докладе Антон расскажет о том, как на эту проблему смотрит Комитет по Стандартизации: какие решения были предложены, и какое стало доминирующим.
An introductory PowerPoint to understanding and applying the C++ programming language. Broken down into lessons covering:
Introduction: Definitions and the History of Programming
Lesson 1: Libraries, Variables and Types, Blocks and Namespaces, Functions
Lesson 2: If...Else Statements, For and While Loops, Scope
Exercise: Program a Gumball Game
Lesson 3: Classes and Objects, Pointers
••• Learn how to safely manage memory with smart pointers! •••
In this presentation you will learn:
▸ the dangers of using raw pointers for dynamic memory
▸ the difference between unique_ptr, shared_ptr, weak_ptr
▸ how to use factories to increase safety and performance
▸ when raw pointers are still needed
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
HotSpot promises to do the "right" thing for us by identifying our hot code and compiling "just-in-time", but how does HotSpot make those decisions?
This presentation aims to detail how HotSpot makes those decisions and how it corrects its mistakes through a series of demos that you run yourself.
••• Boost your code's performances using C++11 new features! •••
In this presentation you will learn:
▸ the difference between an Lvalue and Rvalue
▸ how to use std::move, std::forward, noexcept
▸ how to implement move semantics to avoid useless copies
▸ how to implement perfect forwarding for the factory pattern
Со времён С++98 стандартные контейнеры и идиома RAII позволяли избегать использования оператора delete,
что делало код более безопасным. С приходом С++11 и умных указателей отпала необходимость использовать оператор new, что позволило практически полностью переложить управление памятью на плечи компилятора. В
докладе объясняется идеология управления памятью и ресурсами в современном С++.
На протяжении всего существования C++ тема компайл-тайм рефлексии поднимается постоянно, но, к сожалению, до сих пор Стандарт языка не дает достаточных возможностей для извлечения и манипулирования компайл-тайм информацией. Большое количество библиотек и препроцессоров было придумано для того, чтобы решить эту проблему, начиная от простых макросов и заканчивая Qt-moc или ODB. В докладе Антон расскажет о том, как на эту проблему смотрит Комитет по Стандартизации: какие решения были предложены, и какое стало доминирующим.
An introductory PowerPoint to understanding and applying the C++ programming language. Broken down into lessons covering:
Introduction: Definitions and the History of Programming
Lesson 1: Libraries, Variables and Types, Blocks and Namespaces, Functions
Lesson 2: If...Else Statements, For and While Loops, Scope
Exercise: Program a Gumball Game
Lesson 3: Classes and Objects, Pointers
••• Learn how to safely manage memory with smart pointers! •••
In this presentation you will learn:
▸ the dangers of using raw pointers for dynamic memory
▸ the difference between unique_ptr, shared_ptr, weak_ptr
▸ how to use factories to increase safety and performance
▸ when raw pointers are still needed
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
HotSpot promises to do the "right" thing for us by identifying our hot code and compiling "just-in-time", but how does HotSpot make those decisions?
This presentation aims to detail how HotSpot makes those decisions and how it corrects its mistakes through a series of demos that you run yourself.
After reimplement many features several times in different platforms is time to think that it should be a better way. There are many frameworks that allows the developers to write the code once and deploy it "everywhere", but the final result is an app with a non native look and feel or with an emulated look and feel that the users can see and rate according to the quality.
There are other ways to develop apps for multiple platforms without rewriting the same code over and over. I'll talk about one of that ways which consists on developing the core with C++ and implement the UI natively. This method could sound very scary because of the C++ reputation (memory leaks, the standard library, etc), but with C++11 all this has been improved in a very sweet way, so maybe it is time to take an other look at this language and see how can we take advantage of it.
Azul Virtual Machine Engineer Douglas Hawkins describes how decisions made by the JVM affect how your code is compiled and run. Learn how this affects application performance and what steps you can take to optimize how the JVM acts on your code.
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016STX Next
Kotlin - one of the popular programming languages built on top of Java that runs on JVM. Thanks to JetBrains support and excellent IDE integration, it’s an ideal choice for Android development. 100% Java compatibility, interoperability and no runtime overhead is just the beginning of a long list of strengths. Kotlin is supposed to be a subset of SCALA, on one hand covering major advantages for developers and keeping short compile times on the other.
This presentation is a Developer Starter - a set of hand-picked information allowing a person with no knowledge of Kotlin to start writing basic Android activities and set up a kotlin-based Android project. It starts with language background, reasons for its creation and advantages. Then presents basic use cases, syntax, structures and patterns. Later on Kotlin is presented in Android context. Simple project structure, imports and Kotlin usage with Android SDK is explained. In the end cost of Kotlin compilation is presented and the language is compared to SCALA and SWIFT.
StxNext Lightning Talks - Feb 12, 2016
Kotlin - one of the popular programming languages built on top of Java that runs on JVM. Thanks to JetBrains support and excellent IDE integration, it’s an ideal choice when it comes to Android development. 100% Java compatibility, interoperability and no runtime overhead is just the beginning of a long list of strengths. Kotlin is supposed to be a subset of SCALA, on one hand covering major advantages for developers and on the other - keeping short compile times.
This presentation is a Developer Starter - a set of hand-picked information allowing a person with no knowledge of Kotlin to start writing basic Android activities and set up an Android-kotlin project. It starts with language background, reasons for its creation and advantages. Then presents basic use cases, syntax, structures and patterns. Later on Kotlin is presented in Android context. Simple project structure, imports and Kotlin usage with Android SDK is explained. In the end cost of Kotlin usage is presented and the language is compared to SCALA and SWIFT.
Talk I gave to The Coding Machine about PHP 8. Overview of the RFC process and which QoL, features and notable BC breaks before finishing on some performance improvements.
Online storefront creation: A business creates an online storefront, which serves as its virtual shop where customers can browse products or services, place orders, and make payments.
Product listing: The business lists its products or services on the online storefront, along with relevant information such as price, product description, and images.
Payment gateway integration: The business integrates a payment gateway into its online storefront, which allows customers to securely make payments online using credit cards, debit cards, or other payment methods.
Order processing: When a customer places an order, the business receives the order information through the online storefront. The business then processes the order, which may involve verifying the availability of the product, preparing the product for shipping, and generating a shipping label.
Shipping and delivery: The business ships the product to the customer's address using a third-party logistics provider or its own delivery service. The customer is provided with tracking information to monitor the status of the shipment.
Customer service: The business provides customer service to address any issues or concerns that the customer may have regarding the product or service.
Example:
Let's take the example of a clothing store that sells its products online through its e-commerce website. The store creates an online storefront and lists its products, which include dresses, shirts, pants, and accessories. Customers can browse the products, select the items they wish to purchase, and make payments online using a payment gateway such as PayPal or Stripe.
Once the order is received, the store processes the order and prepares the product for shipping. The product is then shipped to the customer's address using a logistics provider such as FedEx or UPS. The customer can track the shipment using the tracking information provided by the store.
If the customer is not satisfied with the product, they can contact the store's customer service and initiate a return or exchange. The store handles the return or exchange process and ensures that the customer is satisfied with their purchase.
This presentation is about using Boost.Python library to create modules with С++.
Presentation by Andriy Ohorodnyk (Lead Software Engineer, GlobalLogic, Lviv), delivered GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
What Are The Immediate Steps To Take When The VW Temperature Light Starts Fla...Import Motorworks
Learn how to respond when the red temperature light flashes in your VW with this presentation. From checking coolant levels to seeking professional help, follow these steps promptly to prevent engine damage and ensure safety on the road.
𝘼𝙣𝙩𝙞𝙦𝙪𝙚 𝙋𝙡𝙖𝙨𝙩𝙞𝙘 𝙏𝙧𝙖𝙙𝙚𝙧𝙨 𝙞𝙨 𝙫𝙚𝙧𝙮 𝙛𝙖𝙢𝙤𝙪𝙨 𝙛𝙤𝙧 𝙢𝙖𝙣𝙪𝙛𝙖𝙘𝙩𝙪𝙧𝙞𝙣𝙜 𝙩𝙝𝙚𝙞𝙧 𝙥𝙧𝙤𝙙𝙪𝙘𝙩𝙨. 𝙒𝙚 𝙝𝙖𝙫𝙚 𝙖𝙡𝙡 𝙩𝙝𝙚 𝙥𝙡𝙖𝙨𝙩𝙞𝙘 𝙜𝙧𝙖𝙣𝙪𝙡𝙚𝙨 𝙪𝙨𝙚𝙙 𝙞𝙣 𝙖𝙪𝙩𝙤𝙢𝙤𝙩𝙞𝙫𝙚 𝙖𝙣𝙙 𝙖𝙪𝙩𝙤 𝙥𝙖𝙧𝙩𝙨 𝙖𝙣𝙙 𝙖𝙡𝙡 𝙩𝙝𝙚 𝙛𝙖𝙢𝙤𝙪𝙨 𝙘𝙤𝙢𝙥𝙖𝙣𝙞𝙚𝙨 𝙗𝙪𝙮 𝙩𝙝𝙚 𝙜𝙧𝙖𝙣𝙪𝙡𝙚𝙨 𝙛𝙧𝙤𝙢 𝙪𝙨.
Over the 10 years, we have gained a strong foothold in the market due to our range's high quality, competitive prices, and time-lined delivery schedules.
Why Is Your BMW X3 Hood Not Responding To Release CommandsDart Auto
Experiencing difficulty opening your BMW X3's hood? This guide explores potential issues like mechanical obstruction, hood release mechanism failure, electrical problems, and emergency release malfunctions. Troubleshooting tips include basic checks, clearing obstructions, applying pressure, and using the emergency release.
What Does the PARKTRONIC Inoperative, See Owner's Manual Message Mean for You...Autohaus Service and Sales
Learn what "PARKTRONIC Inoperative, See Owner's Manual" means for your Mercedes-Benz. This message indicates a malfunction in the parking assistance system, potentially due to sensor issues or electrical faults. Prompt attention is crucial to ensure safety and functionality. Follow steps outlined for diagnosis and repair in the owner's manual.
"Trans Failsafe Prog" on your BMW X5 indicates potential transmission issues requiring immediate action. This safety feature activates in response to abnormalities like low fluid levels, leaks, faulty sensors, electrical or mechanical failures, and overheating.
Ever been troubled by the blinking sign and didn’t know what to do?
Here’s a handy guide to dashboard symbols so that you’ll never be confused again!
Save them for later and save the trouble!
What Could Cause The Headlights On Your Porsche 911 To Stop WorkingLancer Service
Discover why your Porsche 911 headlights might flicker out unexpectedly. From aging bulbs to electrical gremlins and moisture mishaps, we're delving into the reasons behind the blackout. Stay tuned to illuminate the road ahead and ensure your lights shine bright for safer journeys.
Things to remember while upgrading the brakes of your carjennifermiller8137
Upgrading the brakes of your car? Keep these things in mind before doing so. Additionally, start using an OBD 2 GPS tracker so that you never miss a vehicle maintenance appointment. On top of this, a car GPS tracker will also let you master good driving habits that will let you increase the operational life of your car’s brakes.
Your VW's camshaft position sensor is crucial for engine performance. Signs of failure include engine misfires, difficulty starting, stalling at low speeds, reduced fuel efficiency, and the check engine light. Prompt inspection and replacement can prevent further damage and keep your VW running smoothly.
Learn why monitoring your Mercedes' Exhaust Back Pressure (EBP) sensor is crucial. Understand its role in engine performance and emission reduction. Discover five warning signs of EBP sensor failure, from loss of power to increased emissions. Take action promptly to avoid costly repairs and maintain your Mercedes' reliability and efficiency.
Fleet management these days is next to impossible without connected vehicle solutions. Why? Well, fleet trackers and accompanying connected vehicle management solutions tend to offer quite a few hard-to-ignore benefits to fleet managers and businesses alike. Let’s check them out!
In this presentation, we have discussed a very important feature of BMW X5 cars… the Comfort Access. Things that can significantly limit its functionality. And things that you can try to restore the functionality of such a convenient feature of your vehicle.
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)
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.
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;
}
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