Sunday, May 20, 2007

Comparisons of C++ and Java (II): Static Variables

I used a lot of static variables in Java programming and I don't feel any tricks except you have to know why you make a variable static. I thought it would be the same to use static variable in C++. However, it is not true.

In C++, static data member must be defined outside class definition

In Java, we declare a static variable in class scope and can access it anywhere inside the class. In C++, I thought it must be the same way. Actually it is not. Here is the example. I declare a variable static in head file (test.h) and try to use it in the program file (test.cc) as shown in the sample code:

test.h

class test {
private:
static int i;
public:
test();
}

test.cc
test::test(){
i = 0;
}

At compilation, I get an error says “undefined reference to `test::i”. After I looked up some books and also did some Google search, I finally figured out that a static variable must be defined in the program file. So test.cc should look like:

test.cc

int test::i; //We can also initialize i here, eg. int test::i = 0.
test::test(){
i = 0;
}

Now compiler is happy. But why? The reason is that C++ keeps two files for a class: class declaration (header file) and class definition (program) file. The header file contains the class declaration and does not necessary reserve storage space associated with the identifier, while the program file contains method definitions and reserve storage space for each given identifier.

So when we declare a static data member within a class definition, it is NOT defined. In other words, we are not allocate storage for it. Instead, we must provide a global definition for it elsewhere outside class definition because it does not belong to any specific instance of the class.

What about in Java? Java has a simplified matter by only have class and variable definitions. There are no sole declarations in Java, so class definition and variable definitions are also class declarations and variable declarations. In other words, in Java, all classes, data members and variables within methods are defined, therefore storage spaces are reserved for primitive data types.

In C++, a local variable can be static

In C++, a local variable can be static. For example:

test::test(){

i = 0;

static int count = 0;

}

is perfectly legal in C++. A local static variable has the same life time as a global static variable, but its scope is local to the function in which it is declared. It sounds a good idea to me.

In Java, a static variable can only be declared inside a class scope. Compiler will complain if a local variable is declared as static inside a method scope, Even inner classed cannot have static declarations.








1 comment:

Anonymous said...

Thanks Xiaoyun Tang , The article gave me exactly what i was looking for. Now I understand the concept.Infact I used to think the same way the Java works.
Thanks!!
Ritu