1.124J | Fall 2000 | Graduate

Foundations of Software Engineering

Lecture Notes

Static Class Members

Static Member Data and Static Member Functions

(Ref. Lippman 13.5)

The Point class that we have developed has both member data (properties) and member functions (methods). Each object that we create will have its own variables mfX, and mfY, whose values can vary from one Point to another. In order to access a member function, we must have created an object first e.g. if we want to write

a.print();

then the object a must already exist.

Suppose now that we wish to have a counter that will keep track of the number of Point objects that we create. It does not make sense for each Point object to have its own copy of the counter, since the counter will have the same value regardless of which object we are referring to. We would rather have a single integer variable that is shared by all objects of the class. We can do this by creating a static member variable as the counter. What if we wish to provide a member function to query the counter? We would not be able to access the member function unless we have created at least one object. We would rather have a function that is associated with the class itself and not with any object. We can do this by creating a static member function. The following example illustrates this.

point.h

// Declaration of class Point.

#ifndef _POINT_H_
#define _POINT_H_

#include <iostream.h>

class Point {
// The state of a Point object. Property variables are typically
// set up as private data members, which are read from and
// written to via public access methods.
private:
float mfX;
float mfY;
static int miCount;

// The behavior of a Point object.
public:
Point(float fX=0, float fY=0);        // A constructor that takes two floats.
~Point();                                         // The destructor.
static int get_count();
// …
};

#endif // _POINT_H_

point.C

// Definition of class Point.

#include “point.h”

// Initialize the counter.
int Point::miCount = 0;

// A constructor which creates a Point object from two floats.
Point::Point(float fX, float fY) {
cout << “In constructor Point::Point(float,float)” << endl;
mfX = fX;
mfY = fY;
miCount++;
}

// The destructor.
Point::~Point() {
cout << “In destructor Point::~Point()” << endl;
miCount–;
}

// Accessor for the counter variable.
int Point::get_count() {
return miCount;
}

point_test.C

#include “point.h”

int main() {
cout << Point::get_count() << endl;  // We don’t have any Point objects yet!

Point a;
Point *b = new Point(1.0, 2.0);

    cout << b->get_count() << endl;      // This is allowed, since *b exists.

delete b;

cout << a.get_count() << endl;           // This is allowed, since a exists.

return 0;
}

Course Info

Learning Resource Types
Exams with Solutions
Presentation Assignments
Programming Assignments with Examples
Written Assignments