Thursday, February 07, 2008

Static Members in C++

 

Static in C++ mean the same as that in Java. It is a shared member and all objects of type X will have the same copy of static members of X. Look the simple example:

1 #include<iostream>
2 using namespace std;
3 class Boo;
4 class Foo
5 {
6 public:
7 Foo(){}
8 ~Foo(){cout<<"Foo Destructor called"<<endl;}
9 static Boo b;
10 };
11 class Boo
12 {
13 public:
14 Boo() { cout<<"Boo constructor called"<<endl;}
15 ~Boo() { cout<<"Boo destructor called"<<endl;}
16 string getName(){ return "Krishna";}
17 };
18
19 /*In order to access a static member, you need to declare its scope first*/
20 Boo Foo::b;
21
22 int main()
23 {
24 Foo f; //object Foo() is created;
25 Foo g;
26 cout<<"End of code in main"<<endl;
27 }
This example conveys two important points
  • In order to be able to access static member of Foo outside Foo, you should declare it as in the line 20.

  • The memory for static members is allocated only when this declaration in the file scope is made. In Java, memory for static members is allocated the first time you access that class which owns these members. (For clarity, comment out line 20 and run the code again).

  • Irrespective of the member being accessed or not, this declaration invokes the constructor of Boo.

    No comments: