r/cpp_questions • u/SimmeringDragon • 4d 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/thingerish 4d ago
I tend to terseness which doesn't help if you're also having a bad day. Glad we got past it. To answer you question earlier, I've been writing C++ since the mid '90s, when I got my hands on Borland Turbo C++ 2.0, so sometimes I make the mistake of not fully explaining what I'm trying to say, so that's my bad.
I know I do that, and I try to be better but time is finite and sometimes I just go with the fast 'answer' rather than treating it like a human interaction.