Wednesday, September 1, 2010

Static function members in C+

Static member functions (C++ only)
You cannot have static and nonstatic member functions with the same names and the same number and type of arguments.
Like static data members, you may access a static member function f() of a class A without using an object of class A.
A static member function does not have a this pointer.

Eg.
class X
{
private:
   static int si;
public:
   static void set_si(int arg) { si = arg; }
};


Static member functions (C++ only)
The compiler does not allow the member access operation this->si in function A::print_si() because this member function has been declared as static, and therefore does not have a this pointer.
You can call a static member function using the this pointer of a nonstatic member function. In the following example, the nonstatic member function printall() calls the static member function f() using the this pointer:
#include < iostream >
using namespace std;

class C {
static void f() {
cout << "Here is i: " << i << endl;
}
static int i;
int j;
public:
C(int firstj): j(firstj) { }
void printall();
};

void C::printall() {
cout << "Here is j: " << this->j << endl;
this->f();
}

int C::i = 3;

int main() {
C obj_C(0);
obj_C.printall();
}
 
A static member function cannot be declared with the keywords virtual, const, volatile, or const volatile.
A static member function can access only the names of static members, enumerators, and nested types of the class in which it is declared. Suppose a static member function f() is a member of class X. The static member function f() cannot access the nonstatic members X or the nonstatic members of a base class of X.

No comments:

Post a Comment