0

Just imagine we have the following class:

class A
{
private:
static int m_a;
public:
A() {}
static int get_sum(int b);
};

int A::m_a = 5;

int A::get_sum(int b)
{
return m_a + b;
}

int main() {
    // your code goes here
    A a;
    int c = a.get_sum(10);
    cout << "C=: " << c << endl;
    return 0;
}

In the code above, we have class which contains one private, static member variable which called into our public, static member function get_sum(). Now the question: How the function which has not "this" pointer can access class member variable m_a ? In the Lipman's book I have read that:

(( Point3d* ) 0 )->object_count();

where object_count() does nothing more than return the _object_count static data member. How did this idiom evolve ? ..............................
..............................
//internal transformation of call

object_count(( Point3d* ) 0 );

The language solution was the introduction of static member functions within the official cfront Release 2.0. The primary characteristic of a static member function is that it is without a this pointer.

I don't understand how we can cast 0 to class type object ?

  • 1
    You are casting 0 to a pointer type. Not to a class type. Also static method are usually called like so : `A::get_sum()` not `a.get_sum()`. The point of static members is they are associated with the class itself, not any instance of the class. In fact they are created before any memeber of the class is instanciated. – Félix Cantournet Dec 14 '14 at 19:06
  • Does it mean that every static function has a pointer like this ((class name* ) 0) and using this pointer it can get access to every data member into class ? –  Dec 14 '14 at 19:09
  • 1
    I don't know the implementation details but you can think of it that way I guess. The compiler create an address for the Class from which he addresses static members by offset. So the static member has a address that is constant throughout the lifetime of the program. – Félix Cantournet Dec 14 '14 at 19:29

1 Answers1

0

Static member functions don't have this pointer and static data member is class-specific rather than object-specific. So, static member functions can access static member variables.

ravi
  • 10,994
  • 1
  • 18
  • 36
  • And what about object_count(( Point3d* ) 0 ); internal conversion ? –  Dec 14 '14 at 18:42