Static members
A class can contain static member data and member functions. When a data member is declared as "static," only one copy of the data is reserved for all objects of the class.
Static data members are not part of the object of a given class type. Therefore, the declaration of a static data member is not treated as a definition. Declares a data member in the scope of a class, but executes the definition within the scope of the file. These static class members have external links. The following example illustrates this point:
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 ()
{
}
In the preceding code, the member ByteCount is declared in class Bufferedoutput, but it must be defined outside the class declaration.
You can refer to static data members without referencing objects of the class type. You can get the number of bytes written using the Bufferedoutput object, as follows:
Long nbytes = Bufferedoutput::bytecount;
For static members that exist, the existence of all objects of the class type is not necessary. You can also use member selection (. and –>) operators to access static members. For example:
Bufferedoutput Console;
Long nbytes = Console.bytecount;
In the preceding example, a reference to the object (Console) is not evaluated; The value returned is the value of the static object ByteCount.
Static data members Follow class member access rules, so only class member functions and friends are allowed to have private access to static data members.
Variable data members
This keyword can only be applied to non-static and very data members of a class. Assigning a value to this data member from a const member function is legal if a data member is declared as mutable.
Grammar
Mutable member-variable-declaration;
Note
For example, the following code does not go wrong at compile time because M_accesscount has been declared as mutable and can be modified by Getflag, even if Getflag is a constant member function.
Mutable.cpp
class X
{public
:
BOOL Getflag () const
{
m_accesscount++;
return m_flag;
}
Private:
bool M_flag;
mutable int m_accesscount;
};
int main ()
{
}