Topic... just wondering if it would be friend or pointers in the main or something else...

Dani AI

Generated

asked about sharing state and behavior between two Allegro-based classes; and rightly pushed for clearer use cases (class vs. object-level sharing). A few practical, maintainable approaches that work well for game code:

  • Put shared data and resource handles into a small, explicit "context" or "state" object and pass that to subsystems. This documents ownership and lifetime.
  • Let one higher-level object (engine/mediator) own resources and orchestrate calls between subsystems to avoid tight bidirectional coupling.
  • For loose coupling use narrow interfaces/callbacks or an event/observer system so modules communicate by messages rather than reaching into each other.

Example (context passed by reference—keep the context alive for subsystem lifetimes):

struct SharedContext {
    int score = 0;
    ALLEGRO_BITMAP* sprite = nullptr; // Allegro resource handle
    void reset() { score = 0; }
};

class Renderer {
public:
    Renderer(SharedContext& ctx) : ctx_(ctx) {}
    void render() { /* use ctx_.sprite */ }
private:
    SharedContext& ctx_;
};

class Player {
public:
    Player(SharedContext& ctx) : ctx_(ctx) {}
    void update() { ++ctx_.score; }
private:
    SharedContext& ctx_;
};

int main() {
    SharedContext ctx;
    Renderer rnd(ctx);
    Player pl(ctx);
    // game loop...
}

Notes and cautions: document who owns what and avoid cyclic includes (use forward declarations or interfaces). If the shared state must have dynamic lifetime or shared ownership, prefer std::shared_ptr (see https://en.cppreference.com/w/cpp/memory/shared_ptr). For event-driven decoupling, the Observer pattern is a good fit (see https://en.wikipedia.org/wiki/Observer_pattern).

Recommended Answers

All 4 Replies

For a complete answer, you need to provide a better description of what you're trying to do. What do you mean by "share"? If you just want a function to be visible, make it public. If you want multiple classes to see the same variable, the proper course of action depends on the circumstances.

Topic... just wondering if it would be friend or pointers in the main or something else...

It depends. Can you describe some program cases where you need to share (polysemantic term) variables?

well its in the api allegro, I want two public classes to share variables and use eachothers functions

Classes or (all) objects of these two classes?
Feel the difference...

The simplest way: there lots of global variables in Allegro environment. Add yet another or two ;)...

Seriously: explain use case(s) where you need so tight interrelations. May be it's ONE class splitted to these weird wrecks?..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.