Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a pointer to a C++ object, what is the preferred way to call a static member function?

Say I have:

class A {
public:
    static void DoStuff();

    // ... more methods here ...
};

And later on I have a function that wants to call DoStuff:

B::SomeFunction(A* a_ptr) {

Is it better to say:

    a_ptr->DoStuff();
}

Or is the following better even though I have an instance pointer:

    A::DoStuff()
}

This is purely a matter of style, but I'd like to get some informed opinions before I make a decision.

like image 244
i_am_jorf Avatar asked Nov 26 '22 21:11

i_am_jorf


2 Answers

I think I'd prefer "A::DoStuff()", as it's more clear that a static method is being called.

like image 123
Fred Larson Avatar answered Nov 29 '22 12:11

Fred Larson


It's better to call the static method by its name, not through an object, since it doesn't actually use that object at all. In Java, the same problem exists. A not-too-uncommon problem in Java is the following:

Thread t = getSomeOtherThread();
t.sleep(1000);

This compiles fine but is almost always an error -- Thread.sleep() is a static method that causes the current thread to sleep, not the thread being acted on as the code seems to imply.

like image 36
Adam Rosenfield Avatar answered Nov 29 '22 13:11

Adam Rosenfield