Each instance of a class has its own states. However, we also have static
states allowing us to share a variable between every instance of a class. You can think of a static
state as being a part of the class rather than the objects.
Here is a good example of the use of static states in the Account
class.
1 2 // Static Member Example 3 4 #include<iostream> 5 #include<string> 6 7 using namespace std; 8 9 class Account{ 10 11 protected: 12 13 static int nextAccountNumber;14 int accountNumber; 15 float balance; 16 string owner; 17 18 private: 19 20 void construct();
21 22 public: 23 24 Account(string owner, float aBalance); 25 Account(float aBalance); 26 27 virtual void display(); 28 virtual void makeLodgement(float); 29 virtual void makeWithdrawal(float); 30 }; 31 32 int Account::nextAccountNumber = 123456;
33 34 Account::Account(string anOwner, float aBalance): 35 balance(aBalance), 36 owner (anOwner) { construct(); }
37 38 Account::Account(float aBalance) : 39 balance(aBalance), 40 owner ("Not Defined") {construct(); } 41 42 void Account::construct() 43 { 44 accountNumber = nextAccountNumber++;
45 } 46 47 void Account::display(){ 48 cout << "account number: " << accountNumber 49 << " has balance: " << balance << " Euro" << endl; 50 cout << "This account is owned by: " << owner << endl; 51 } 52 53 void Account::makeLodgement(float amount){ 54 balance = balance + amount; 55 } 56 57 void Account::makeWithdrawal(float amount){ 58 balance = balance - amount; 59 } 60 61 int main() 62 { 63 Account *a = new Account("John", 10.50); 64 Account *b = new Account("Derek", 12.70); 65 66 a->display(); 67 b->display(); 68 } 69 70
(The full source code for this example is here -
StaticMemberTest.cpp
)
The output of this example can be seen in Figure 3.18, “The Account
class with static state example output.”.
Static variables can be public
, private
or
protected
.
Static member methods can be defined in the same way (e.g.
static int getNextAccountNumber();
). Static member methods cannot access non-static states and they
cannot be virtual, as they are related to the class and not the object.
© 2006
Dr. Derek Molloy
(DCU).