C++ calling member functions statically
-
Naive programmer question time... I'm reviewing some old code (not mine) for my employer and have found that some member functions are being called statically. Is this good practice? Is there any benefit to calling member functions statically? Example code structure as below.
class MyClass { //... public: void fn2() {//...} void fn1() {MyClass::fn2();} // why not just fn2() ? };
Is there a reason/benefit why fn2() gets called statically? Both fn1 and fn2 alter the calling object. Neither fn affects any static class data. MyClass is not invloved in any inheritance.Matt
-
Naive programmer question time... I'm reviewing some old code (not mine) for my employer and have found that some member functions are being called statically. Is this good practice? Is there any benefit to calling member functions statically? Example code structure as below.
class MyClass { //... public: void fn2() {//...} void fn1() {MyClass::fn2();} // why not just fn2() ? };
Is there a reason/benefit why fn2() gets called statically? Both fn1 and fn2 alter the calling object. Neither fn affects any static class data. MyClass is not invloved in any inheritance.Matt
It isn't a static member function, so it isn't being called statically. Instead, it is being called explicitly. If it were a virtual function, then you would be guaranteeing to call the given class implementation (or the one it inherits, but there isn't any inheritance in this case. There's no real advantage/disadvantage in this case, except that the compiler is being explicity told to use MyClass::fn2() rather than this->fn2().
Steve S Developer for hire
-
It isn't a static member function, so it isn't being called statically. Instead, it is being called explicitly. If it were a virtual function, then you would be guaranteeing to call the given class implementation (or the one it inherits, but there isn't any inheritance in this case. There's no real advantage/disadvantage in this case, except that the compiler is being explicity told to use MyClass::fn2() rather than this->fn2().
Steve S Developer for hire
Thanks for the explanation.
Matt