Wednesday, December 23, 2009

Static Variable in C++

Static Variable in C++:

You have to define the static data member outside the class declaration.

When you declare a variable or function at file scope (global and/or namespace scope), the static keyword specifies that the variable or function has internal linkage. When you declare a variable, the variable has static duration and the compiler initializes it to 0 unless you specify another value.

When you declare a variable in a function, the static keyword specifies that the variable retains its state between calls to that function.

When you declare a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. A static data member must be defined at file scope. An integral data member that you declare as const static can have an initializer.

When you declare a member function in a class declaration, the static keyword specifies that the function is shared by all instances of the class. A static member function cannot access an instance member because the function does not have an implicit this pointer. To access an instance member, declare the function with a parameter that is an instance pointer or reference.



//statictest.h

class

statictest

{

public:

static int a;

void sum();

};

///////////////////////////////////////////////

//statictest.cpp

#include "statictest.h"

int statictest::a; // Defining outside the class. By default value of a=0.

void statictest::sum(){

a=0;

}

///////////////////////////////////////////////

//main.cpp

#include "statictest.h"

int main()

{

statictest test;

test.sum();

}

///////////////////////////////////////////////


#include

using namespace std;
class CMyClass {
public:
static int m_i;
};

int CMyClass::m_i = 0;
CMyClass myObject1;
CMyClass myObject2;

int main() {
cout << myObject1.m_i << endl;
cout << myObject2.m_i << endl;

myObject1.m_i = 1;
cout << myObject1.m_i << endl;
cout << myObject2.m_i << endl;

myObject2.m_i = 2;
cout << myObject1.m_i << endl;
cout << myObject2.m_i << endl;

CMyClass::m_i = 3;
cout << myObject1.m_i << endl;
cout << myObject2.m_i << endl;
}


Output--
0
0
1
1
2
2
3
3

No comments:

Post a Comment