I want to make a class, let’s name it class A, that executes functions from other classes. So I want to inherit my classes from this A class and class A to be able to receive function addresses from the derived classes and execute them.
This is what I thought so far:
#include <iostream>
using namespace std;
template <class T>
class A
{
public:
// a typedef for the function I want to execute
// which has no parameters and void as return type
typedef void (T::*SpecialFunc)();
A() { }
//this is the function that executes the received functions
void exec(SpecialFunc func)
{
((new T)->*func)();
}
};
class B : public A<B>
{
public:
B()
{
// call A::exec to call my function
exec(&B::funcB);
}
//function I want to be executed
void funcB()
{
cout << "testB\n";
}
};
int main()
{
B ob;
return 0;
}
What I want is function funcB to be called. So far my program breaks with no error, just heavily breaks.
I know that this code can’t work because I try to build class A that needs information from class B and class B needs information from the first class A to be constructed but I hope you understand better what I’m willing to achieve.
Can this be achieved?
Thank you
Looks like you have infinite recursion here. You call
exec()in constructor ofB, it creates newBobject bynewstatement which calls constructor ofBwhich callsexec()etc. Probably you need to pass ponter or reference toBobject toexec()to avoid its construction.And of course
Bobject leak inexec()doesn’t look good. I hope it’s just for testing purposes…