#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2002
    Posts
    7
    Rep Power
    0

    Question c++ equivalent to java's static class members


    Hi,

    in java, it's possible to declare a class member - be it a function or a variable - as static, thus creating a member that, e.g, holds the same value regardless of instantiation. It is not a constant though, as it stays accessible for all instances of the class which, in case it is a variable, may change it.

    I am learning c++ and bought a book which doesn't mention anything like static class members.

    Is there or is there not an equivalent construct in c++?

    any answers appreciated

    costas
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,648
    Rep Power
    4248
    Yes there is and it's declared using the keyword static as well. Here's some sample code using a static variable.

    Code:
    #include <iostream>
    class test {
      static int counter;
    public:
      int getcount() { return counter;}
      test();
    };
    
    int test::counter = 0;
    
    test::test() {
      counter++;
    }
    
    int main(void) {
      test foo, bar;
    
      cout << foo.getcount() << "\n";
    }
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2002
    Posts
    7
    Rep Power
    0
    hey, thanks a lot.:)

    so, it's more or less identical to the java syntax. I guess, it's the same with functions?

    BTW, this makes me feel bad about the quality of the book I bought. I mean, it does focus mainly on developement under Linux with c++, but it explains the syntax in detail...or so I thought.:confused:

    one more time, thanks, however

IMN logo majestic logo threadwatch logo seochat tools logo