Thursday, August 03, 2006

Static member function in C++

What are static members?

Static members are members that exist indepently from an instantiation of a class. They are share by all instances of that class, and can be used without requiring an instance. (static variable must be defined in .cpp file)

When should use static member function?

When you want to use the member function without instantiate a class, you have to define it as static.

class A
{
public:
static int k;
A () {i=5;}
void noChangeClassMember() const
{
i = 6;
printf("%d\n", i);
}
static void changeClassMember() {
printf("hello\n");
i =10; // wrong, i is not static
}
private:
mutable int i;
};
int A::k = 0;
// main( )
A::changeClassMember(); // good
A::noChangeClassMember(); // wrong, cannot call non-static fun
A ab;
ab.noChangeClassMember(); //OK

Summery (coudersource.net)

1. A static member function can access only static member data, static member functions and data and functions outside the class. A non-static member function can access all of the above including the static data member.

2. A static member function can be called, even when a class is not instantiated, a non-static member function can be called only after instantiating the class as an object.

3. A static member function cannot be declared virtual, whereas a non-static member functions can be declared as virtual

4. A static member function cannot have access to the 'this' pointer of the class.

Some other notes from thinkinginc++ (update on Jan. 30, 2008)
Normally, the address of the current object (this) 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.

remember the check the static member function application singleton pattern.

No comments:

Post a Comment