1

Given three classes:

class A {
    B* b_;
    A(B* b){
        b_ = b;
    }

    void doThings() {
        C* c = new C(b_);
        ...
        // Use c
    }
}

class B {}

class C {
    B* b_;
    C(B* b) {
        b_ = b;
        ...
    }
}

The reference to B in class A is useful only for passing it to C when needed, because A and C cannot create instance of B.

I am wondering if I could avoid having the reference in A using some design pattern: I do not think making B a singleton is a good solution and I think that a Factory could be better, but maybe is an over complication.

Is the unused reference a real problem? Does a factory solve my problem?

  • 1
    It's hard to answer without more details of the problem. On it's face, however, just having the pointer to B is not problem as long as there's a reasonable guarantee about the lifetime of B – Mike Lui Mar 2 '17 at 19:39
1

pass c into the constructor for A

class A {
    C* c_;
    A(C* c){
        c_ = c;
    }

    void doThings() {
        ...
        // Use c_
    }
}

class C {
    B* b_;
    C(B* b) {
        b_ = b;
        ...
    }
}
1

It looks like an instance of C should be an argument to the doThings method. C is not a class-wide dependency, and _b only serves as a dependency to C, therefore something else should create C and pass it to doThings.


You'll have to forgive me, I haven't written c++ since... college? Pointer/reference syntax might be a tad off.


class A {
    A() { }

    void doThings(C* c) {
        // Use c
    }
};

class B { };

class C {
    B* _b;

    C(B* b) {
        _b = b;
    }
};

Something has to coordinate between A, B and C:

class X {
    void doStuff() {
        B b;
        C c(&b);
        A a;

        a.doThings(&c);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.