Mike
Mike

Reputation: 65

CRTP - How to call the base class implemention of a method from the derived class?

I am currently messing around with the CRTP pattern using C++ templates. While fiddling around with visual studio i found several ways/methods in which a derived class can call the base class implementation of a function. Below is the code i am using and also 3 commented out lines showing how call the base class implementation of a function from a derived class. Is there a benefit to using one method over another? Are there any differences? What is the most comonly used method?

template<typename T>
struct ConsoleApplication
{

    ConsoleApplication()
    {
        auto that = reinterpret_cast<T*>(this);
        that->ShowApplicationStartupMsg();
    }



    void ShowApplicationStartupMsg()
    {

    }
};


struct PortMonitorConsoleApplication : ConsoleApplication < PortMonitorConsoleApplication >
{
    void ShowApplicationStartupMsg()
    {
        // __super::ShowApplicationStartupMsg();
        // this->ShowApplicationStartupMsg();
        // ConsoleApplication::ShowApplicationStartupMsg();
    }
};

Upvotes: 0

Views: 1662

Answers (2)

Rubix Rechvin
Rubix Rechvin

Reputation: 581

The preferred method I've seen is to use this:

ConsoleApplication::ShowApplicationStartupMsg();

This is nice since it is very clear what you're trying to do, and what parent class the method being called is from (especially useful if you're not the parent class itself is a derived class).

Upvotes: 1

dascandy
dascandy

Reputation: 7302

ConsoleApplication < PortMonitorConsoleApplication >::ShowApplicationStartupMsg();

Use the full name of your base class.

Note that this->ShowApplicationStartupMsg() doesn't call your base, it calls your own function again.

__super isn't standard (and shouldn't become one, as it's ambiguous with multiple bases).

using ConsoleApplication:: is not entirely standard (although I think GCC accepts it) as you don't inherit from ConsoleApplication per se, just one specific instance of it.

Upvotes: 0

Related Questions