4.5. Static Class Members

In our procedural implementation of Chapter 2, we maintain one container instance to hold the elements of the Fibonacci sequence through use of a local static vector. Our class implementation also needs only one container instance to hold the elements of each numeric sequence. The static keyword again provides the solution, although it means something different when used within a class.

A static data member represents a single, shared instance of that member that is accessible to all the objects of that class. In the following class definition, for example, we declare _elems as a static data member of the Triangular class:

class Triangular { 
public: 
   // ... 
private: 
   static vector<int> _elems; 
}; 

Because only a single ...

Get Essential C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.