Thursday, 26 March 2015

Static member functions implementation in C++

Static member functions implementation in Cpp with examples:

There is possibility that it is possible to create the static member functions that, like static data members , work for the class as a whole rather than for a particular object of a class.
How to call the static member function?

Call a static member function by itself, without any specific object, using the scope-resolution operator.

Syntax of the static member function calling as shown below:
class TestStaticFun

  static void MyStaticFun ()
    { };
int main ()
  TestStaticFun:: MyStaticFun  ();

There are two things we need to remember that
1. A static member function cannot access ordinary data members, it can access only static data members.

2. A static member function can call only other static member functions.

Normally, the address of the current object is quietly passed in when any member function is called, but a static member has no this, which is the reason it cannot access ordinary members. Thus, you get the tiny increase in speed afforded by a global function because a static member function doesn’t have the extra overhead of passing this. At the same time you get the
benefits of having the function inside the class.

For data members, static indicates that only one piece of storage for member data exists for all objects of a class. This parallels the use of static to define objects inside a function to mean that only one copy of a local variable is used for all calls of that function.
Here’s an example showing static data members and static member functions used together:

class ClassX
  int m_iVal;
  static int m_stVal;
  ClassX (int iVal = 0) : m_iVal(iVal)
    { m_stVal= m_iVal; }
  int val () const { return m_iVal; }
  static int incr()
    { return ++m_stVal; }
  static int TestStaticFunc()
    { return incr (); }
int ClassX::m_stVal= 0;
int main ()
  ClassX ClassX;
  ClassX* pcObjX = &ClassX;
  ClassX::TestStaticFunc ();   
  getchar ();
  return 0;

As the result
1>  TestCPP.cpp

1>TestCPP.cpp(106): error C2065: 'pcObjX' : undeclared identifier

1>TestCPP.cpp(108): error C2065: 'pcObjX' : undeclared identifier

1>TestCPP.cpp(108): error C2227: left of '->TestStaticFunc' must point to class/struct/union/generic type

1>          type is ''unknown-type''

========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Because they have no this pointer, static member functions can neither access non-static data members nor call non-static member functions.

Notice in main () that a static member can be selected using the usual dot or arrow syntax, associating that function with an object, but also with no object using the class name and scope resolution operator.

No comments: