C++
Static methods
Learn static methods and how to call them without an instance.
static methods
A static method can be called with the class name, without creating an instance. The static int getCount() declaration makes the method static.
Inside a static method there is no this pointer, so it can only access static members. To reach an instance member you need an object. Call: Player::getCount(). This works even without a Player instance. Static methods are ideal for grouping helper functions and counter accessors.
Limits of static methods
Because a static method has no this pointer, it cannot access instance members directly. Trying to reach an instance member like id gives a compile error.
On the other hand, static members like count are accessible, because they belong to the class, not to an instance. This restriction keeps static methods working as helpers that do not depend on an instance. If you need to access an instance member, do not make the method static; leave it as a regular method.
Exercise Add a static getCount to the Player class
Add static int count; and count++ in the constructor to the Player class. Under public: add static int getCount() with body return count;. Outside the class write int Player::count = 0;. In main create two Player objects and write std::cout << Player::getCount();.
Show example solution
#include <iostream>
class Player {
public:
static int count;
static int getCount() { return count; }
Player() { count++; }
};
int Player::count = 0;
int main() {
Player p1;
Player p2;
std::cout << Player::getCount();
return 0;
}
Test yourself
-
Complete the static method declaration
class Player { public: ____ int getCount() { return count; } };
Show answer
class Player { public: static int getCount() { return count; } };
-
Which can be accessed from a static method?
class Player {
int id;
static int count;
static int get() { }
};
- count
- id
- this->id
- this->count
Show answer
count — A static method can only access static members.
-
Match each piece to its role
- static int get()
- Static method
- Player::get()
- Call
- this
- Absent in static
- count
- Accessible
Next lesson: static const