PDA

View Full Version : Is there the static class in C++?



gtthang
21st February 2006, 17:54
When I read some documents about the design, I usually meet this word but I'm not very familiar with it in C++.
Thanks for caring!

Codepoet
21st February 2006, 18:56
I don't know what you mean by "static class".
In C++ you can have static members or functions in a class. These are not bound to any instance but instead are "class global".

Definition:


class C
{
public:
static int a;
static void f() {cout << a << "\n";}
void m() {cout << a << "\n";}// normal method
};

int C::a = 21;


Usage:


C c1, c2;
cout << c1.a << " " << c2.a << "\n";// normal way to access
c1.a = 42;
cout << C::a << "\n";// static access
C::f();// static access
c1.f(); c2.f();
C::a = 21;
c1.g(); c2.g();



And there's another meaning of static when refering to variables in implementation files: These variables are file-local when declared static.

rh
21st February 2006, 20:54
Possibly confusing C++ with C#? A C# class (since .Net 2.0) can be declared static indicating it contains only static members.

probine
24th February 2006, 17:23
C# allows you to have static classes and all members inside the class must be static.
C++ allows you to declare static members inside a class.
After instantiating the class many times, all the static fields are going to have the same value in all instances.

rh
25th February 2006, 06:46
C++ allows you to declare static members inside a class.
After instantiating the class many times, all the static fields are going to have the same value in all instances.

Of course a regular C# class or struct can contain static members just as in C++ with the same effect. The static class declaration is just sugar so the compiler can enforce no instanance members have been added to the class and that the class itself cannot be instantiated. You could accomplish the same thing using all static members and a private constructor.

I only mentioned it in the first place because C# is the only language that i personally know of that actually has a declaration for a static class.