I have a class like::
Class Test
{
public:
void Check(){//dosomething};
static void call(){//I want to call check()};
};
Because call() is a static member, so it can't call non-static functions, so I think to use Check() in call() is to create Test pointer and then point to Check(), but I think it is not good, is there a better way to do this? I can rewrite all of things in the static function, so I don't need to call Check() again, but what I want is to reuse the code in Check() and avoid repeated code.
This sounds like there is some bad design going on.
Anyhow, what you can do, is create an instance of Test in call, and call Check on that instance. The implementation of call would be something like this then:
However, note that if Check does something with the members of Test, it will ofcourse only apply to the created Test object. I would rethink whether you really want call to be static, or Check not to be.
The key different between a non-static and a static member function is that the latter doesn't have any object. It still has the same access privileges like all other members, however.
When you want to call a non-static member function from a static member, you still need to come up with an object, however. Often, the static member function would get passed in some context to get to an object. From the sounds of your question it seems that the static and the non-static functions are meant to do similar things which don't require and object. In this case it is probably best to factor the common part, not depending on any object, into another function which is then called from both
call()
andCheck()
:If the common code needs an object, there is no other way than coming up with an object in your static member function.
There's no simple answer to this. There are various things you could do, but which is right depends on what your code means. It's a design question, not a programming question.
You've already suggested various programming tricks you could do, like creating a
Test
pointer (actually you don't need aTest
pointer, just aTest
object). I could suggest more tricks, for instance you could rewritecall()
so that it's not static, or (very nearly the same thing) you could pass aTest
pointer as a parameter ofcall()
and use that, or you could create a globalTest
object and use that. None of these get to the heart of the problem. To answer your question you have to ask yourself questions like, why did I makecall()
static in the first place, why does a static function need to call a non-static function.If you can explain that, then it's easier to give more specific advice.
Since you need an instance, you either have to create one, use a static instance, or pas it to
call()
: