[Dprglist] Help with C++ design patterns

Rud Merriam rudmerriam at gmail.com
Sun Mar 7 15:39:25 PST 2021


I wouldn't call this a patter, just a technique.

A reference member must be initialized in the constructors 
initialization list. It cannot be done through assignment. I'm surprised 
the compiler didn't generate a syntax error with your code. But then the 
Arduino system does weird stuff with the code which satisfies the 
compiler but is not correct at run time. Have to see an actual simple 
example to tell.

The other possibility is you haven't created the class. In the code 
below A must be initialized before it can be passed to B;

class A {

};

class B {

public:

     B(A& a) :    // by refernce
         mA{a} {}

     B(A* a);    // by pointer
         mAPtr{a};

private:

     A& mA;
     A* mAPtr;
}

A a;
B b{a};        // by ref
B b_ptr{&a};   // by ptr




-73 -
*Rud Merriam K5RUD*
/Mystic Lake Software/ <http://mysticlakesoftware.com/>

On 3/7/21 8:32 AM, Carl Ott via DPRGlist wrote:
>
> Can somebody help with C++ design patterns?
>
> I have a class with many methods (first class), that needs access to 
> members of another class (other class).
> Surely I can pass a reference to the other class into every method of 
> the first class.
> But that seems like a verbose pain.
> Instead, I'd like to initialize the first class with a reference or 
> pointer to the other class. Then the first class could use the cached 
> reference or pointer to the other class whenever it's needed.
> However, I'm missing something - not getting it to work.
>
> Am I just missing syntax or am I fundamentally trying to implement an 
> anti-pattern?
>
> What are some best practices design patterns to accomplish this?  Any 
> recommendations - where to find a quick tutorial?
>
>
> here's an abstract of what isn't working...
>
> class needsToStoreAreference
> {
>
>     public:
>
>         cacheAreference(otherClass &desiredReference);
>
>     private:
>
>         otherClass &storedReferenceToOtherClass;
>
> }
>
> needsToStoreAreference::cacheAreference(otherClass &desiredReference)
> {
>
>     storedReferenceToOtherClass = desiredReference;
>      // doesn't work, causes an Arduino program to hang
>
> }
>
>
>
> And in the calling code
>
> needsToStoreAreference instanceOfNeedsToStore(); // instance of 'first 
> class' in wording above
>
> otherClass instanceOfOtherClass(); // instance of 'other class' in 
> wording above
>
> instanceOfNeedsToStore.cacheAreference(instanceOfOtherClass);
>
>
> _______________________________________________
> DPRGlist mailing list
> DPRGlist at lists.dprg.org
> http://lists.dprg.org/listinfo.cgi/dprglist-dprg.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.dprg.org/pipermail/dprglist-dprg.org/attachments/20210307/085971f1/attachment.html>


More information about the DPRGlist mailing list