jeudi 23 avril 2015

container class member interaction

I'd like to get some advice on how I can improve my overall program design.

I have a main class which has two members that frequently need to interact with each other. This container-like class has an Initialize() function which initializes both of the members, and other functions which provide access to the outside world:

class Foo {
public:
    bool InitializeAandB();
    void UseFoo();

private:
    TypeA a;
    TypeB b;
};

At some point after UseFoo() is called, a will need access to b. So, let's say TypeA has a member function like this:

void TypeA::Function() {
if(true) {
TypeB *bpointer;
bpointer->Interact(); //Need access to b here.
 }
}

TypeA and TypeB are separate entities and cannot be combined into a single class. It just so happens that these separate entities need to interact with each other at various times.

I don't want to make a and b public because they shouldn't be visible from the outside world. Adding TypeA and TypeB as friends in Foo seems like a hacky fix. Also not ideal because then both TypeA and TypeB need to know about Foo when they only need to know about each other. Same goes for public GetA() and GetB() accessor functions.

A third option is to add a TypeB* member to TypeA and a TypeA* member to TypeB which are set during InitializeAandB(). But this seems redundant on some level, like I'm missing a better overall design.

Is there a better way to design this?

Aucun commentaire:

Enregistrer un commentaire