I am having trouble getting my pointers to work correctly. In my main file I declare
Analysis2 analysis = Analysis2();
MaxResults maxresults = MaxResults( analysis);
Now in my MaxResults class, I want to point to analysis so that if any of its variables change I still get the right value. Right now I declare the constructor in the MaxResults header as
MaxResults(Analysis2 analysis);
Analysis2 * analysis2;
And in the MaxResults class
MaxResults(Analysis2 analysis)
{
analysis2 = analysis;
}
When I try to access things from analysis that changed, analysis2 doesn’t seem to be keeping up. How do I fix this, and is there an easy way to remember pointers and referencing and dereferencing in the future?
If you want
MaxResultsto keep a pointer to anAnalysis2object, you should do it like this:and construct it like this:
Note the use of the address-of operator (&) to capture the address of
analysisand pass it as pointer to theMaxResultsconstructor, which saves the pointer in a member (using an initialization list, which is more or less equivalent to doinganalysis = anin the constructor’s body, just in case the:syntax is new to you).For further reading, have a look at references (once your got a better understanding of pointers, of course). In this case, references would probably be preferred.