Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static function call non static function in C++ [closed]

Tags:

c++

static

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.

like image 735
CJAN.LEE Avatar asked Nov 11 '12 13:11

CJAN.LEE


2 Answers

Since you need an instance, you either have to create one, use a static instance, or pas it to call():

Class Test
{
  private:
  static Test instance;

  public:
  void Check(){//dosomething};
  // use one of the following:
  static void call(Test& t){ t.check(); };
  static void call(){ Test t; t.check(); };
  static void call(){ instance.check(); };
};
like image 96
Axel Avatar answered Oct 05 '22 20:10

Axel


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:

void call(){
  Test test;
  test.Check();
}

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.

like image 25
W. Goeman Avatar answered Oct 05 '22 21:10

W. Goeman