Thursday, October 27, 2011

Static Member Functions in C++

In this post I make some notes about static member functions in C++.

  1. Static member functions belong to and can be accessed via the class. Also, it can be accessed via objects of the class type, but it's not recommended.
  2. Static member functions have no implicit this pointer, since the this pointer always points to the object that the member function is working on.
  3. Static member functions can only access the names of static members, enumerators, and nested types of the class in which it is declared.
  4. Even when accessing static members in static member functions, this pointer is not allowed.
  5. Static member functions can be accessed via this pointer in other nonstatic member functions.
  6. Static member functions cannot be declared with the keywords virtual, const, or volatile.
  7. Static member functions cannot have the same name as a nonstatic member function that has the same argument types. In other words, the keyword static is not part of function signature.
  8. Pure static class (has static members and static membe functions only) is dangerous like global variables.
  9. Pure static class cannot have multiple copies without cloning and renaming.
  10. Operator overloading functions of a class cannot be static member functions
  11. Pointers to member cannot be used to point to any static member, including static member functions.
  12. The left side of a member-selection operator (. or ->) that selects a static member function is not evaluated. For example, the expression SideEffects().CountOf() does not call the function SideEffect.

I checked the last item and found some conflicting results. Here is an example (actually counter-example) for that item. In my example, the left side function call was actually executed, either passing arguments or not.

The output is:
0
in increaA
1
in increaA
2
in decreaA
1
in decreaA
0


References:
Microsoft MSDN library
IBM publib
LearnCpp.com

No comments:

Post a Comment