Programming & Scripting Tutorials

C++: Static





When objects are created from the same class each instance has its own copy of the class variables.
But this is not the case when it is declared as static.

To declare a variable static you simply use the static keyword like so:

static int Integer1;


Statics in classes can be quite annoying though, for example you can't initialise statics inside the classes, only declare them.
That's why in this lesson we are also going to cover some other ways to access things in classes.
But firstly take a look at this to see how statics work in action:


#include <iostream>
#include <string>
using namespace std;

class Party{
public:
    string firstname
    string lastname;
    static int peopleatparty;
    Party(string first, string last){
    firstname = first;
    lastname = last;
    peopleatparty++;
	cout << "Welcome to the party " <<  firstname << " " << lastname << "\nPeople:" << peopleatparty << endl;
    }
};

int Party::peopleatparty = 0;

int main(){
Party Person1("Bob", "Smith");
Party Person2("Jill", "Anderson");
Party Person3("Fred", "Savage");
system("PAUSE");
return 0;
}



Ok. so most of the above is pretty obvious, the only bit you probably wont understand is this line:

int Party::peopleatparty = 0;

All this does is go into the Party class and then set people at party to 0.
We use int as a type specifier as C++ does not support default assumptions.

You can set any variables in classes using this method, but it must be outside of any classes, methods and/or functions.


This C++ tutorial was written by


Back to C++

Advertisement: