Tuesday, October 27, 2009

callback and static member functions

you can not use non-static member functions as callback.because class member functions have a hidden argument i.e. this pointerpointing to the object.while for callbacks you need to have a function with exact declaration/signature.So you can't pass 'this' in the callback.On the other hand Static member functions do not have this pointer as they can be called without making an instance of class.So if you want to use a CLASS MEMBER FUNCTION for callback.It must be declared as static.Also static declaration is given inside class definition only,while define the function in cpp you don't give the keyword 'static'

static memeber not allowed inside C struct

Sumit does it again.
He gave me a programm which doesn't compile and asked the reason which I could not tell him,
have a look at the following snippet,
struct mystruct

{
float foo;
static int bar;//This line generates compilation error.
};

This is a perfectly valid c++ code,and bar can be accessed as mystruct::bar.
And it means that 'bar' will be shared accross all instances of mystruct.
But the scope resolution operator
is in C++ only,concept of name scoping as it exists in C++ was not there.
C is much more closer to machine.Also at the time of C being designed
It was never thought that they may need to share a var across different instances.
Also in C ,struct is not a user defined type instead it is just a collection of heterogenic
items.
So this code is not allowed in C.

Saurabh