Click here to Skip to main content
15,920,801 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
1.I have confusion in understanding why do we need static member functions? 2.What happens when we declare static member functions? 3.What does it means when static member functions have class scope or belong to class rather than objects of the class?
Posted

Static functions are those that operate only on static data - they are not related to any instance of the class, and cannot access or call any non-static variables or functions. They do not have a this pointer.

You access trhen differently too - via the class name, rather than via an instance variable.
 
Share this answer
 
Comments
Abhinay Kumar 29-Feb-12 5:26am    
Is it possible to access them through objects of the class?If they do not have this pointer how is it possible to call them through objects of the class?
OriginalGriff 29-Feb-12 5:35am    
You can call them through an instance, but it is not a good idea - it implies that they are non-static, which they aren't. Even if you do, they do not get a "this" pointer, so cannot access anything.
MyClass::MyStaticFunction();
is a lot more obvious than
myclassInstance.MyStaticFunction();
In answer to question 1, "Why do we need static member functions?"

I've used them in the past when I wanted to use a member function as a WNDPROC.
Since you can't use a non-static method as the callback that WndProc is, you need to create a static method. Then from within that static method you must determine which c++ object instance is pertinant to the particular window.

The practise leaves one feeling a little unlean, and is known as Thunking.


I first came across this use in the source-code for Win32++[^]
I'd assume that similar code was found within MFC
 
Share this answer
 
Comments
barneyman 29-Feb-12 18:15pm    
Win callbacks, or thread-entry points

Anywhere else, and you get a withering look and a "please explain"
if you need to add some behavior which affect every instance of that class, static method and properties do it for you.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900