const static member functions

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Rahul Joshi

    const static member functions

    Hi,

    Is it possible to define static member functions that are 'const',
    i.e. they just read but do not modify the static data members of
    a class? Declaring functions like:

    class SomeClass {
    static int read() const;
    };

    gives compiler errors, so it seems this is not directly supported.
    Is there any other way in which I can get this effect?

    Thanks,
    Rahul

  • Victor Bazarov

    #2
    Re: const static member functions

    "Rahul Joshi" <rujoshi@studen ts.uiuc.edu> wrote...[color=blue]
    > Is it possible to define static member functions that are 'const',
    > i.e. they just read but do not modify the static data members of
    > a class? Declaring functions like:
    >
    > class SomeClass {
    > static int read() const;
    > };
    >
    > gives compiler errors, so it seems this is not directly supported.[/color]

    Correct. There is no object associated with the function (classes
    are not objects in C++), so nothing to make obtain the const-ness
    from.
    [color=blue]
    > Is there any other way in which I can get this effect?[/color]

    What effect? Constant member functions are chosen in overload
    resolution over non-constant ones when called with a constant
    object (and vice versa). How would the compiler use the 'const'
    with a function that doesn't have an object associated with it?

    If you know that you're implementing a function that is supposed
    not to change the static data, just don't change them.

    Victor


    Comment

    • Shane Beasley

      #3
      Re: const static member functions

      Rahul Joshi <rujoshi@studen ts.uiuc.edu> wrote in message news:<Pine.GSO. 4.31.0307151344 050.6212-100000@ux5.cso. uiuc.edu>...
      [color=blue]
      > Is it possible to define static member functions that are 'const',
      > i.e. they just read but do not modify the static data members of
      > a class?[/color]

      Not really, no.
      [color=blue]
      > Declaring functions like:
      >
      > class SomeClass {
      > static int read() const;
      > };
      >
      > gives compiler errors, so it seems this is not directly supported.
      > Is there any other way in which I can get this effect?[/color]

      You could implement the Singleton design pattern (i.e., a single,
      static instance of class SomeClass) and make read() a const,
      non-static member function which operates on the instance. Or,
      depending on your intentions, you could make the relevant static data
      members const.

      That's about it, really.

      - Shane

      Comment

      Working...