Skip to Content
Hands-On Design Patterns with C++
book

Hands-On Design Patterns with C++

by Fedor G. Pikus
January 2019
Intermediate to advanced
512 pages
14h 5m
English
Packt Publishing
Content preview from Hands-On Design Patterns with C++

Compile-time polymorphism

As we have just seen, CRTP can be used to allow the derived class to customize the behavior of the base class:

template <typename D> class B {    public:    ...    void f(int i) { static_cast<D*>(this)->f(i); }    protected:    int i_;};class D : public B<D> {    public:    void f(int i) { i_ += i; }};

If the base class B::f() method is called, it dispatches the call to the derived class method for the real derived class, just like a virtual function does. Of course, in order to fully take advantage of this polymorphism, we have to be able to call the methods of the base class through the base class pointer. Without this ability, we are simply calling methods of the derived class whose type we already know:

D* d = ...; // Get an object ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Structural Design Patterns in Modern C++

Structural Design Patterns in Modern C++

Umar Lone

Publisher Resources

ISBN: 9781788832564Supplemental Content