[Dprglist] Help with C++ design patterns

Jian Shi jshi.fyu at gmail.com
Sun Mar 7 14:59:49 PST 2021


Hi Carl,

Can you save the reference in a pointer? i.e. "otherClass*
storedReferenceToOtherClass"
The pattern seems ok.

I think you need to initialize the reference in the constructor, otherwise
the field "otherClass &storedReferenceToOtherClass" doesn't have a valid
state.

Regards,
-Jian

*Jian Shi*

Phone: +1 805-680-6412

Email: *jshi.fyu at gmail.com <jshi.fyu at gmail.com>*


On Sun, Mar 7, 2021 at 8:32 AM Carl Ott via DPRGlist <
dprglist at lists.dprg.org> 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/cb12cc85/attachment.html>


More information about the DPRGlist mailing list