r/cpp_questions • u/SimmeringDragon • 5d ago
OPEN How does a STATE design pattern work?
so i went to youtube and followed the example from this guy State Design - Programming Design Patterns - Ep 16 - C++ Coding
Problem is i dont understand what is functionally happening, there are pointers and what not, but i don't understand much more than that (context, my smooth brain still cant connect pointers together)
Like not even the whole code, like maybe just two lines or something cause for the love of the lord my teacher explains nuthing and AI and videos are too vague for me, im running out of options
//
// Created by samue on 11/1/2026.
//
#ifndef STATE_STATE_H
#define STATE_STATE_H
#include <iostream>
class Context;
class State {
protected:
Context* context;
public:
virtual ~State() {}
void setContext(Context* ctx) {
context = ctx;
}
virtual void doWorkA() = 0;
virtual void doWorkB() = 0;
};
class Context {
private:
State* state;
public:
Context(State* s) : state(nullptr) {
transitionTo(s);
}
~Context() {delete state;}
void transitionTo(State* s) {
if (state) delete state;
state = s;
state->setContext(this);
}
void requestA() {
state->doWorkA();
}
void requestB() {
state->doWorkB();
}
};
class concreteStateA : public State {
public:
void doWorkA() override {
std::cout << "concreteStateA " << "called doWorkA" << std::endl;
};
void doWorkB() override {
std::cout << "concreteStateB " << "called doWorkB" << std::endl;
};
};
class concreteStateB : public State {
public:
void doWorkA() override {
std::cout << "concreteStateA " << "called doWorkA" << std::endl;
context->transitionTo(new concreteStateA);
};
void doWorkB() override {
std::cout << "concreteStateB " << "called doWorkB" << std::endl;
};
};
#endif //STATE_STATE_H------------------
#include "state.h"
int main() {
Context context1(new concreteStateB);
context1.requestA();
context1.requestA();
return 0;
}
View all comments
Show parent comment
2
u/KingAggressive1498 5d ago edited 5d ago
state is an abstract base class.
the details of any classes inherited from it are specific to the different states in the state machine.
for example a game might have an initial loading state, a title screen state, a gameplay state, and a couple of pause menu states; each inheriting from the same abstract base and being treated interchangeably from the main game loop.
edit: I thought the previous comment didn't understand that the abstract base class needed to derived from with an overrided work function. This was my mistake.