CodeBlanks Logo Icon CodeBlanks

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.

Practice 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();.

Starter code

main.cpp
#include <iostream>

// Define the Player class here

int main() {
    // Create two Players and print getCount
    return 0;
}

Sample solution

main.cpp
#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;
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the static method declaration

Question
class Player { public: ____ int getCount() { return count; } };
Answer
class Player { public: static int getCount() { return count; } };

Explanation: The static keyword makes the method callable without an instance.

2 Which can be accessed from a static method?

main.cpp
class Player {
    int id;
    static int count;
    static int get() { }
};
  • count Correct answer
  • id
  • this->id
  • this->count

Explanation: A static method can only access static members.

3 Match each piece to its role

Term Meaning
static int get() Static method
Player::get() Call
this Absent in static
count Accessible

All lessons in Intermediate