Archive for August 23rd, 2007

Static member variables in C++ class…

Thursday, August 23rd, 2007

I was thought I am an expert on C++, however today I still found something very simple BUT I didn’t know… It’s all about define a static variables in C++ class… :(

Static data members are not part of objects of a given class type; they are separate objects. As a result, the declaration of a static data member is not considered a definition. The data member is declared in class scope, but definition is performed at file scope. These static members have external linkage.

So the code should like this:

// static_data_members.cpp
class BufferedOutput
{
public:
   // Return number of bytes written by any object of this class.
   short BytesWritten()
   {
      return bytecount;
   }

   // Reset the counter.
   static void ResetCount()
   {
      bytecount = 0;
   }

   // Static member declaration.
   static long bytecount;
};

// Define bytecount in file scope.
long BufferedOutput::bytecount;

int main()
{
}

Shame I am…


Popularity: 11% [?]

Close
E-mail It
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License.