Topic: Why can't static member functions be co


Author: etxmlkn@aom.ericsson.se (Mikael Karlsson)
Date: Tue, 26 Jul 1994 09:10:31 GMT
Raw View
Oops, sorry guys seems like my posting got corrupted so everything was not sent.
Here is the REAL example and my questions.

#include <iostream.h>


class A
{
  static int b;
public:
  A() {}
  static const char* StaticGetConst() const
   { return "A";}
  static const char* StaticIncGetConst() const
   { b++; return "A";}    // No error - Huh ??
  static int StaticInc()
   { return b++;}
  static int StaticIncConst() const
   { return b++;}              // Error line 18:
  int Inc()
   { return b++;}
  const char * ConstMethodCallingStaticGet() const
   {return A::StaticGetConst();}
  int ConstMethodCallingStatic() const
   { return StaticInc(); }
  int ConstMethodCallingNonStaticNonConst() const
   {return A::Inc();}     // Warning line 26 - Good!
};

main ()
{
 const A a;
 cout << a.ConstMethodCallingStaticGet() << endl;
 cout << a.ConstMethodCallingStatic() << endl;
 cout << a.ConstMethodCallingNonStaticNonConst() << endl;
}

% CC main2.cc
"main2.cc", line 18: error:  StaticIncConst() static member function cannot be const
"main2.cc", line 26: warning: non-const member function A::Inc() called for const object (anachronism)

Notes:
1 - const member functions can't (should not) change the object. See warning.
2 - static members functions don't need objects to operate
3 - (Some) static member functions can not be const. See error message.
4 - const member functions CAN call OTHER object's non const member functions.
    The const-ness is defined as no changes on the object itself.

Questions:
  - static member function may be called from const member functions which
    modifies 'class data'. See ConstMethodCallingStatic().
    I guess the reason is that it does not change the objects data, however
    can't the 'class data' be seen as the data of all-objects-of-the-class and
    therefore it should not be changable from no object's non const method ???
 - Why may some static member functions be const but others wont ?,
   see StaticGetConst(), StaticIncGetConst(), StaticIncConst().
   (compiler bug ??)
 - I'm using a Sun CC2.1 compiler and the question is how you should interpret the
   error message (line18-msg): static member functions can not be const in general
   or THIS PARTICULAR static member function can not be const. ???

/Mikael