C++/Static Function...
Expert: vijayan - 8/19/2009
QuestionVijayan,
Have small query about static function and constructor. Basically, static function can access only static variable and static member function. In certain circumstance, how come static function can access constructor?... (Since, constructor is special member non-static function. Thru static function we can create object.) like below example...
class Sample {
private : Sample() { }
public:
static Sample* make()
{
Sample s = new Sample();
return s;
}
};
AnswerA static member function is not an operation on an object instance, it can be called without an object instance, and has no this pointer. So it can not access the non-static members of the class without an object instance, because there is no object instance passed to it by default. But it is not restricted in any other way; anything that a normal non-member function can do, a static member function can also do. For example,
class Sample
{
private :
Sample() {}
int non_static_member ;
public:
static Sample* make()
{
Sample s = new Sample();
return s;
}
static another_static_member_function( Sample* object )
{
non_static_member = 7 ; // *** error, there is no object, no this->non_static_member
object->non_static_member = 7 ; // fine, access non_static_member of object
Sample s = new Sample(); // fine, you are not accessing an existing object, but creating a new one
s->non_static_member = 7 ; // fine, access non_static_member of s
}
};