You are here:

C++/Static Function...

Advertisement


Question
Vijayan,

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;
        }
};  

Answer
A 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
         
         
      }
};

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.