C++: Declaring Static Member Functions - dummies

C++: Declaring Static Member Functions

By Stephen R. Davis

Member functions can be declared static in C++. Static member functions are useful when you want to associate an action to a class, but you don’t need to associate that action with a particular object.

For example, the member function Duck::fly() is associated with a particular duck, whereas the rather more drastic member function Duck::goExtinct() is not.

Like static data members, static member functions are associated with a class and not with a particular object of that class. This means that, like a reference to a static data member, a reference to a static member function does not require an object. If an object is present, only its type is used.

Thus, both calls to the static member function number() in the following example are legal. This example is a simple static program — a program using static members — CallStaticMember:

// CallStaticMember - demonstrate two ways to call a
//                    static member function
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
class Student
    Student(const char* pN = "no name") : sName(pN)
    ~Student() { noOfStudents--; }
    const string& name() { return sName; }
    static int number() { return noOfStudents; }
    string sName;
    static int noOfStudents;
int Student::noOfStudents = 0;
int main(int argcs, char* pArgs[])
    // create two students and ask the class "how many?"
    Student s1("Chester");
    Student* pS2 = new Student("Scooter");
    cout << "Created " << s1.name()
         << " and "    << pS2->name() << endl;
    cout << "Number of students is "
         << s1.number() << endl;
    // now get rid of a student and ask again
    cout << "Deleting " << pS2->name() << endl;
    delete pS2;
    cout << "Number of students is "
         << Student::number() << endl;
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    cout << "Press Enter to continue..." << endl;
    cin.ignore(10, 'n');
    return 0;

This program creates two Student objects, one locally and one off the heap. It then displays their names and the count of the number of students. Next the program deletes one of the students and asks the class how many students are out there. The output from the program appears as follows:

Created Chester and Scooter
Number of students is 2
Deleting Scooter
Number of students is 1
Press any key to continue...

This class keeps its data members protected and provides access functions that allow outside (non-Student) code to read but not modify them.

Declaring the return type of name() method to be string& rather than simply string causes the function to return a reference to the object’s existing name rather than create a temporary string object. Adding the const to the declaration keeps the caller from modifying the class’s name member.