Cpp - static Member Functions

Introduction

static member functions exist not in an object but in the scope of the class.

They can be called without having an object of that class.

Demo

#include <iostream> 
 
class Dog /*from   ww  w  . jav  a 2 s.  c o m*/
{ 
public: 
    Dog(int newAge = 1):age(newAge){ howManyDogs++; } 
    virtual ~Dog() { howManyDogs--; } 
    virtual int gGetAge() { return age; } 
    virtual void setAge(int newAge) { age = newAge; } 
    static int getHowMany() { return howManyDogs; } 
private: 
    int age; 
    static int howManyDogs; 
}; 
 
int Dog::howManyDogs = 0; 
 
void countDogs(); 
 
int main() 
{ 
    const int maxDogs = 5; 
    Dog *gestalt[maxDogs]; 
    int i; 
    for (i = 0; i < maxDogs; i++) 
    { 
           gestalt[i] = new Dog(i); 
           countDogs(); 
    } 
 
    for (i = 0; i < maxDogs; i++) 
    { 
           delete gestalt[i]; 
           countDogs(); 
    } 
    return 0; 
} 
 
void countDogs() 
{ 
    std::cout << "There are " << Dog::getHowMany() 
            << " Dogs.\n"; 
}

Result

Related Topic