This course has already ended.

Class Variables and Class Functions

According to: Rintala, Jokinen. Olioiden ohjelmointi C++lla.

When designin the program class structure, it is possible to find things that belong to the responsibilities of a class but not to the reponsibilities of any single object. Those things belong to the entire class. For example, a Date class could have a vector that contains the length of each month or the program could have for testing purposes a counter for the amount of object created from the class and a function that returns this information.

Class Variables: static member variables

In C++, variables common to the class and meant for all class objects and declared as static member varibales. A member variable is made static when its declaration starts with the key word static:

//object.hh
class Object {
public:
   Object();
private:
      static unsigned int objects_;
};

//object.cc
unsigned int Object::objects_ = 0; //initialization of the class variable

Object::Object()
{
       objects_++; //class variable shared by all class objects
}

The class variable does not belong to any object as it is shared by all class objects. Hence the class variable cannot be initialized in the constructor initialization list. Instead, it must be initialized separately. This is usually done in the same file with the implementation of member functions.

Class Functions: static member functions

Similarly to class variables, services that handle the entire class instead of one object can be defined. These include functions that handle class variables and other class wide operations. A class function is declared by starting the declaration with the keyword static.

//object.hh
class Object {
public:
    ....
    static unsigned int Objects();
};

unsigned int Object::Objects()
{
    return objects_;
}

Note! The definition of a class function cannot refer to member variables, member functions or the object itself with the this pointer.

Posting submission...