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 }
Irrespective of the member being accessed or not, this declaration invokes the constructor of Boo.
No comments:
Post a Comment