Question

class A{

    virtual int foo1(int a){ 

        return foo1_1(a,filler(a));
    }   

    template<typename FunctionPtr_filler> 
    int foo1_1(int a, FunctionPtr_filler ptrFn)
    {   
        int b;
        b = (this->*ptrFn)(a);  // --> compile error: pointer to member type int (B::)(int) incompatible with object type A
        return b;
    }   

    protected:
    virtual int filler(int a){ 
        return a*a;
    }   
};

class B: public A{
    virtual int foo1(int a){ 
        return foo1_1(a, &B::filler);
    }   
    virtual int filler(int a){ 
        return (a+a);
    }   
};

Is their any way to overcome this error. I want to pass the filler function and avoid the code smell of duplicate code.

Was it helpful?

Solution

I think the issue here is that you are passing as a parameter the following:

&B::filler

This is a pointer-to-member-function of a function defined in B. In the base class, you are trying to call it as

(this->*ptrFn)(a);

The problem here is that if the receiver object isn't actually an object of type B, this would cause a serious runtime error, because you'd be calling a method in B on an object whose type wasn't B. C++ is giving you a compiler error to tell you that this is not allowed.

To fix this, change the call to pass in

&A::filler

This is a method in A, so any A object will have this particular method. C++ will automatically resolve the call virtually to refer to the most derived implementation of that method, so it should call the B version of the function in this case.

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top