[Dprglist] Help with C++ design patterns

Carl Ott carl.ott.jr at gmail.com
Sun Mar 7 14:32:05 PST 2021


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);
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.dprg.org/pipermail/dprglist-dprg.org/attachments/20210307/c8530f15/attachment.html>


More information about the DPRGlist mailing list