Helpful Information
 
 
Category: C Programming
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

Yes there is and it's declared using the keyword static as well. Here's some sample code using a static variable.



#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";
}

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










privacy (GDPR)