There are nine rules to access objects in class hierarchies. Let’s have a closer look.
Here are the nine rules.
Accessing objects in a hierarchy rule summary:
- C.145: Access polymorphic objects through pointers and references
- C.146: Use
dynamic_castwhere class hierarchy navigation is unavoidable
- C.147: Use
dynamic_castto a reference type when failure to find the required class is considered an error
- C.148: Use
dynamic_castto a pointer type when failure to find the required class is considered a valid alternative
- C.149: Use
shared_ptrto avoid forgetting to
deleteobjects created using
- C.150: Use
make_unique()to construct objects owned by
- C.151: Use
make_shared()to construct objects owned by
- C.152: Never assign a pointer to an array of derived class objects to a pointer to its base
- C.153: Prefer virtual function to casting
Believe me. Slicing is an issue in a lot of C++ codebases.
If you access a virtual function, you don’t know which class provides the functionality; therefore, you should use a pointer or a reference. This means in the concrete example, that both d are sliced.
The first and the second slice cause only the B part of D to be copied.
Do you want to know more about slicing? C.67: A base class should suppress copying, and provide a virtual clone instead if “copying” is desired talks about this issue.
The three next rules are about dynamic_cast. Before I write about the dynamic_cast let me emphasise, casts, including dynamic_cast are used way too often. The job of the dynamic_cast is to “Safely converts pointers and references to classes up, down, and sideways along the inheritance hierarchy.” (http://en.cppreference.com/w/cpp/language/dynamic_cast)
Here is the use case from the C++ Core Guidelines. You want to navigate in the class hierarchy.
To detect the right type for pb (1) during run-time, a dynamic_cast is necessary. If the cast fails, you will get a null pointer.
Because of performance reasons, you want to make the cast at compile-time; therefore, a static_cast is your friend. Now, you can violate the type of safety of the program.
Casting a pointer to B to a pointer to D (1) is an error. This maybe holds for the last line (2).
dynamic_cast to a reference type when failure to find the required class is considered an error
If you make a dynamic_cast to a pointer, you will get, in the case of a failure a null pointer; but if you make a dynamic_cast to a reference, you will get a failure. To be more specific, you will get a std::bad_cast exception.
The g++-6 compiler complains about both bad dynamic_cast’s and the run-time throws the expected exception in case of the reference.
dynamic_cast to a pointer type when failure to find the required class is considered a valid alternative
Sometimes it may be a valid option to choose an alternative code path, if the dynamic_cast to a pointer type fails and, therefore, returns a null pointer.
Using std::unique_ptr or std::shared_ptr is a very important but also quite an obvious rule to avoid resource leaks. If you build an application and not infrastructure such as a library, let me rephrase it: Never ever use new (and delete).
Applying this rule means using std::make_unique and std::make_shared for creating smart pointers.
make_unique() to construct objects owned by
unique_ptrs, C.151: Use
make_shared() to construct objects owned by
Both rules are pretty similar; therefore, I can handle them together. std::make_unique and std::make_shared give you the guarantee that the operation is never interleaved. That means in the following example: no memory leak can happen.
This guarantee will not hold for the next call.
Foo may be at first allocated on the heap, and then bar is called. If bar throws an exception, Foo will not be destroyed, and we will get a memory leak.
The same observation holds for std::make_share for creating a std::shared_ptr. std::make_shared has an additional performance benefit. Creating a std::shared_ptr requires two memory allocations; one for the resource and one for the counter. By using std::make_shared, both expensive allocations will happen in one step. The performance difference is dramatic. Look at my post: Memory and Performance Overhead of Smart Pointers.
This may not happen so often, but the consequences may be terrible if it happens. The result may be invalid object access or memory corruption. The former issue is shown in the example.
The last assignment should update the x attribute of an instance of B, but it overwrites the y attribute of a D. The reason is that B* was assigned a pointer to an array of derived objects D.
Decay is the name of an implicit conversion that applies lvalue-to-rvalue, array-to-pointer, and function-to-pointer conversions removing const and volatile qualifiers. In the concrete example, you can call a function accepting a D* with an array of D‘s. The argument d of the following function will have a pointer to the first element of D. Valuable information, such as the length of the array of D‘s, is lost.
You can use dynamic_cast to simulate virtual behavior also often called late binding. But that is ugly and error-prone. You may get a null pointer or a std::bad_cast exception (see C.147). If you want to know more about virtual functions, read rule C67 in the post C++ Core Guidelines: Rules for Copy and Move.
In C++, we can overload functions, function templates, and even operators. In particular, operator overloading is often very controversial and discussed. For example, MISRA C++, a guideline for a safe subset of C++, forbids the overloading of operators. To be honest. I don’t see why? The C++ Core Guidelines have ten rules for overloading that will be the topic of my next post.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, and Marco Parri Empoli.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,