Question

I have the following situation. This is the stripped down version of the class. I'm running it in Qt creator and using Qt in the real scenario.

class MyClass
    {
    public:
         MyClass();
         static MyClass *instance;
         static void myMethod(int a, int b);
         int name;
    };

    MyClass  *MyClass::instance = 0;

    MyClass::MyClass(){
    if (instance)
        exit(-1);
    instance = this;
    }

void MyClass::myMethod(int a, int b){
        if(instance->name == a) qDebug() << "hello";
    }

int main(int argc, char *argv[])
{
    MyClass cls;
    cls.myMethod(1,2);
}

I'm trying to debug myMethod by stepping into it with the debugger. When i enter the method, only the a 1 and b 2 are visible in the watch and there is no reference to this or instance.

Update The answers stated that static methods are not bound to the object which is why there is no this available.

In this implementation, the static method accesses the instance and that's what I'd like to have available in the debugger once i step into myMethod.

How would I make that available/visible?

Was it helpful?

Solution

Static methods are actually called without an object. The call

MyClass cls;
cls.myMethod(1,2)

is equivalent to

MyClass::myMethod(1, 1)

As a consequence myMethod is not receiving any this value.

OTHER TIPS

Such behavior is to be expected, since a static method has no access to this, as it is not bound to an object.

Simple solution from this answer :

You cannot access a non static member inside a static method unless you explicitly make available the object instance inside the member function.(Pass object instance explicitly as argument or use a global instance which can be accessed inside the function)

That means to change the method into this :

static void myMethod(MyClass instance, int a, int b);

The reason is that static methods don't act on any object and there is no this. Actually, it's quite unusual to call static function on an object. This would do the same and is the more usual way to call satic functions:

int main(int argc, char *argv[])
{
    MyClass cls;
    MyClass::myMethod(1,2); //look Ma, no object!
}

With this it becomes obvious that the cls object is not needed at all in your example code, so you could leave it out entirely. The same applies to the arguments to main, since you don't use them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top