Static methods

Just as a class's data can be made static, so can its methods.

 

In this respect they act like global functions and are accessed like object members of a class.

 

Since static methodsĀ are members of the whole class and not of any instance of an object, they can:

  • only use a class's static data
  • not use non-static members
  • not use the keyword this, as it uses a pointer to an object
  • be called independently, even if no object exists
  • be accessed using the scope resolution operator ::

 

If access to a class's private data member is required, we would normally write a public accessor (get) method. However, this would require instantiation of a class object to access the function. Therefore in the case of static data, we write a public static method to return the static data.

 

#include <iostream>
using namespace std ;

class Humanoid{

public:
	static int qtyHumans ;
	Humanoid() ;
	~Humanoid() ;
    static int getCount() ;
} ;

//initialise static member of Humanoid class
int Humanoid::qtyHumans = 0 ;

int Humanoid::getCount(){return qtyHumans ;}

Humanoid::Humanoid(){
	cout << "Object #" << qtyHumans++ << " created!" << endl ;
}

Humanoid::~Humanoid(void){
	cout << "Object #" << --qtyHumans << " destroyed!"<< endl ;
}

int main () {

	//be sure to use the () parentheses when using a method
	cout << "In the beginning there were " << Humanoid::getCount() << " Humanoids!"<< endl ;
	cout << "But they bred..." << endl ;
	Humanoid simon ;
	Humanoid penny ;
	Humanoid jimmy ;
	Humanoid julia ;
	cout << "Creating " << Humanoid::getCount() << " Humanoids!"<< endl ;
	cout << "So we killed them..." << endl  ;

	return 0;
}

Compile & Run:

In the beginning there were 0 Humanoids!
But they bred...
Humanoid #0 created!
Humanoid #1 created!
Humanoid #2 created!
Humanoid #3 created!
Creating 4 Humanoids!
So we killed them...
Humanoid #3 destroyed!
Humanoid #2 destroyed!
Humanoid #1 destroyed!
Humanoid #0 destroyed!

 

 

Or even simpler, not even creating any objects and just using the static method:

#include <iostream>
using namespace std ;

class Humanoid{

private:
	static int qtyHumans ;

public:
    static int getCount(){
    	return ++qtyHumans ;
    } ;
} ;

//initialise static member of Humanoid class
int Humanoid::qtyHumans = 0 ;

int main () {

	for (int i=0; i<6; i++){
		cout << "Accessing static method " << Humanoid::getCount() << " times" << endl ;
	}

	return 0;
}
Accessing static method 1 times
Accessing static method 2 times
Accessing static method 3 times
Accessing static method 4 times
Accessing static method 5 times
Accessing static method 6 times

Leave a Reply