Search code examples
c++dispatch

Difference between func() and (*this).func() in C++


I am working on someone else code in C++, and I found a weird call to a certain function func(). Here is an example:

if(condition)
    func();
else
    (*this).func();

What is the difference between func() and (*this).func()?

What are the cases where the call to func() and (*this).func() will execute different code?

In my case, func() is not a macro. It is a virtual function in the base class, with an implementation in both base and derived class, and no free func(). The if is located in a method in the base class.


Solution

  • There actually is a difference, but in a very non-trivial context. Consider this code:

    void func ( )
    {
        std::cout << "Free function" << std::endl;
    }
    
    template <typename Derived>
    struct test : Derived
    {
        void f ( )
        {
            func(); // 1
            this->func(); // 2
        }
    };
    
    struct derived
    {
        void func ( )
        {
            std::cout << "Method" << std::endl;
        }
    };
    
    test<derived> t;
    

    Now, if we call t.f(), the first line of test::f will invoke the free function func, while the second line will call derived::func.