class A {
doFunction(void(*f)()){ f(); }
}
class B : public A {
int b;
void func() { b = 1; cout << b << endl; }
doFunc() { doFuntion(&func); }
}
I see the obvious problems with this. doFunction requires void(*)() and doFunc is passing void(B::*)(). I know it seems odd that I would want to do this, but it's just a very small part of what I am trying to accomplish. I need to have the base class A be able to call a function from derived class B, and this function cannot be virtual.
Any help is appreciated.
In A::doFunction you are calling f without any reference to a B object, to which object should that function be applied?
Can you be a bit more specific about what you actually need?
Is there a way I can reference a B object even though B is derived from A?
Specifically, B::func() is a function that modifies B's members. I need A::doFunction to call func() in a way it still modifies B's members.
class B;
struct A {
void doFunction(void(B::*f)());
};
struct B : public A {
int b;
void func() { b = 1; cout << b << endl; }
void doFunc() { doFunction(&B::func); }
};
void A::doFunction(void(B::*f)())
{
B someobject;
(someobject.*f)();
}
Is there I can do this with A not knowing at all about B by using templates? I am not well versed in polymorphism. The end result of what doFunction will be used for is something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class A {
void doFunction(void(*f)()) { f(); }
};
class B : public A {
int b;
void func() { b = 1; cout << b << endl; }
void doFunc() { doFuntion(&func); }
};
class C : public A {
int c;
void func() { c = 1; cout << c << endl; }
void doFunc() { doFuntion(&func); }
};
Thank you both for you help so far. guestgulkan, I think that is a bit closer to what I need. Would something like this work?
1 2 3 4 5 6 7 8 9 10 11 12
template <typename T>
class A {
void doFunction(void(T::*f)()){
((T*)this)->f();
}
}
class B : public A<B> {
int b;
void func() { b = 1; cout << b << endl; }
void doFunc() { doFuntion(&func); }
}