Cpp - static Member Data

Introduction

static member variables are shared among all instances of a class.

A static member belongs to the class rather than to the object.

Normal member data is one per object, but static members are one per class.

The following code uses static member data to track object instance count.

Demo

#include <iostream> 
 
class Dog //w ww .j a  va2 s .com
{ 
public: 
    Dog(int newAge = 1):age(newAge){ howManyDogs++; } 
    virtual ~Dog() { howManyDogs--; } 
    virtual int getAge() { return age; } 
    virtual void setAge(int newAge) { age = newAge; } 
    static int howManyDogs; 
 
private: 
    int age; 
}; 
 
int Dog::howManyDogs = 0; 
 
int main() 
{ 
    const int maxDogs = 5; 
    Dog *gestalt[maxDogs]; 
    int i; 
    for (i = 0; i < maxDogs; i++) 
           gestalt[i] = new Dog(i); 
 
    for (i = 0; i < maxDogs; i++) 
    { 
           std::cout << "There are "; 
           std::cout << Dog::howManyDogs; 
           std::cout << " Dogs left!\n"; 
           std::cout << "Deleting the one which is "; 
           std::cout << gestalt[i]->getAge(); 
           std::cout << " years old\n"; 
           delete gestalt[i]; 
           gestalt[i] = 0; 
    } 
    return 0; 
}

Result

Related Topics