www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C++ Tutorial - Lesson 23: Static Members and Methods

Introduction, Static Members

by John Kopp

Support this site at no cost to you

Introduction
Welcome to EasyCPlusPlus.com's free tutorial on C++ programming. This lesson covers static class members and methods. Static members provide a way to create objects that are shared by an entire class, rather than being part of a particular instance of the class, an object. Static methods provide a way to access and update static members.

Static Members
Suppose it's necessary to keep track of some data that's related to a class as a whole, rather than to a particular object or instance of that class. A simple example is a count of the total number of objects instantiated. Maybe we have an Employee class and we want to keep track of the total number of employees. We could create a global variable to hold this data.

class Employee
{
    ....
}

int numEmployees;

main()
{
    Employee janitor;
    numEmployees++;

    Employee manager;
    numEmployees++;

    .....
}

While this approach will work, it has a major short fall. The global variable, numEmployees is not really related to the class Employee. Ideally, we want all data associated with the class to be encapsulated within that class. Although in this simple example it is obvious that numEmployees pertains to the Employee class, in larger programs the relationship might not apparent. The static keyword provides a way to declare that an object is to be shared by all instances of a class. Here's an example.

Previous Page       Next Page