Home > Blockchain >  c : A function pointer as a parameter. But the function being pointed is declared with Parent class
c : A function pointer as a parameter. But the function being pointed is declared with Parent class

Time:12-10

Its like a riddle. So lets explain one by one.

  • I have a driver function(fD) which receives a function pointer and calls it multiple times in while loop.
  • The function pointer(fP) has a parameter of class A.
  • There are 3 child classes of class A, class B,C,D.
  • I want fP to be able to receive all child classes B,C,D in place of parameter A.
  • Sqwiggle error saying B doesn't match with A.

And of course an example is better than a riddle.

class A {};
class B : A { /* some function */ };
class C : A { /* some function */ };
class D : A { /* some function */ };

void fD(A a, void (*fP)(A))
{
    for (int i = 0; i < 10; i  )
    {
        fP(a);
    }
}

void PointedFunction(B b)
{
    /* Do Something with the B function */
}

void PointedFunction2(C c)
{
    /* Do Something with the C function */
}

void PointedFunction3(D d)
{
    /* Do Something with the D function */
}
int main()
{
    // What i want to do
    B b;
    fD(b, &PointedFunction);
    C c;
    fD(c, &PointedFunction);
    D d;
    fD(d, &PointedFunction);
    // But sqwiggle at & saying argument don't match

    return 0;
};

Question: How can I use child classes in place of parent class in a function pointer?

I'm prettry sure the cause is because I'm trying to use a child class. Since c is very strict about these stuff. But... I don't know how to solve this.

Also, as long as i know, what I'm doing looks very inappropriate to me. Is this like.. legal?

CodePudding user response:

I think this is what you may want to do:

class A {};
class B : public A {};
class C : public A {};
class D : public A {};

void fD(A& instance, void (*fP)(A&))
{
    for (int i = 0; i < 10; i  )
    {
        fP(instance);
    }
}

void PointedFunction(A& a)
{
    /* Do Something with the A family */
}

int main()
{
    B b;
    fD(b, &PointedFunction);
    C c;
    fD(c, &PointedFunction);
    D d;
    fD(d, &PointedFunction);

    return 0;
};

Alternatively, if you have specialized methods for B and C, you may use generics instead of a class hierarchy.

class A {};
class B {};
class C {};

template<class T>
void fD(T& instance, void (*fP)(T&))
{
    for (int i = 0; i < 10; i  )
    {
        fP(instance);
    }
}

void PointedFunction(B& a)
{
    /* Do Something with B */
}

void PointedFunction(C& a)
{
    /* Do Something with C */
}

int main()
{
    B b;
    fD(b, &PointedFunction);
    C c;
    fD(c, &PointedFunction);

    return 0;
};
  • Related