A place to breathe

Thursday, August 28, 2008

Static in C++

I think the keyword "static" in C++ is the most confusing. First of all, the behavior is not the same as in C, and within C++, the behavior is different between variable and function.

Generally, we can think of the keyword static to mean to have the variable to be "global" i.e, can be seen/used by any function within the program execution. But this is a limited definition. The static keyword in C/C++ means more than that.

In C:
1. Global entity declared as static is only "global" for that particular file. Other files cannot see that global variable. (Confused?).
The "file" is referred to as "translation unit". It meant to refer to as "statically allocated". Don't get confused. Just think of a file as a "translation unit", and the static variable can be seen only by the functions defined in that file.

In C++, it was fixed by introduction of "namespace".

In C++:
1. static object:
An object defined within a function, and the value persists across lifetime of a program.

2. static member:
A member variable that is associated with the class itself, rather than the object of the class. The idea is to provide a sort of "global" access, but with the object-oriented enforcement. Just think about that - you can use a static member to store some values visible to those who declared the class. Whether you can modify the static member or not, it depends on whether the static member is declared as public or private.

OK, the one that we want to give attention is this - how static members behave?

Static Function:

1. No "this" pointer: Static member has no object attached to it, so you can't access it with "this" pointer.
2. Cannot use virtual andconst with them. I'm not going into this (maybe later).

Static Variable

1. We cannot specified static variable inside body class, except with following keyword const (e.g static const int num = 78;)
2. Static variable must be defined outside the class


By the way, why do you care about keyword static? Ask yourself.

3 comments:

jiinjoo said...

you care because 4 out of 5 interviews for a software engineering job in a top notch company will ask you to differentiate the keyword static in C, C++ and Java. ;)

Unknown said...

wow, that's good to know. ;).

Unknown said...

Actually, I have no idea what's static mean in Java (maybe because I couldn't care less - I don't like the language, LOL).

About Me

I'm currently a software engineer. My specific interest is games and networking. I'm running software company called Nusantara Software.