Using the class access operators with static members (C++ only)

You do not have to use the class member access syntax to refer to a static member; to access a static member s of class X, you could use the expression X::s. The following example demonstrates accessing a static member:

#include <iostream>
using namespace std;

struct A {
  static void f() { cout << "In static function A::f()" << endl; }
};

int main() {

  // no object required for static member
  A::f();

  A a;
  A* ap = &a;
  a.f();
  ap->f();
}

The three statements A::f(), a.f(), and ap->f() all call the same static member function A::f().

You can directly refer to a static member in the same scope of its class, or in the scope of a class derived from the static member's class. The following example demonstrates the latter case (directly referring to a static member in the scope of a class derived from the static member's class):

#include <iostream>
using namespace std;

int g() {
   cout << "In function g()" << endl;
   return 0;
}

class X {
   public:
      static int g() {
         cout << "In static member function X::g()" << endl;
         return 1;
      }
};

class Y: public X {
   public:
      static int i;
};

int Y::i = g();

int main() { }

The following is the output of the above code:

In static member function X::g()

The initialization int Y::i = g() calls X::g(), not the function g() declared in the global namespace.

Related information



[ Top of Page | Previous Page | Next Page | Contents | Index ]