Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer trouble

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?

like image 882
mrswmmr Avatar asked Jan 18 '26 09:01

mrswmmr


2 Answers

If you want MaxResults to keep a pointer to an Analysis2 object, you should do it like this:

class MaxResults {

 public:
     MaxResults(Analysis* an) : analysis(an) {}

 private:
     Analysis* analysis;
};

and construct it like this:

Analysis2 analysis = Analysis2();
MaxResults maxresults = MaxResults( &analysis);

Note the use of the address-of operator (&) to capture the address of analysis and pass it as pointer to the MaxResults constructor, which saves the pointer in a member (using an initialization list, which is more or less equivalent to doing analysis = an in 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.

like image 71
Alexander Gessler Avatar answered Jan 20 '26 01:01

Alexander Gessler


I'm not really sure how that's compiling; it shouldn't. The problem is your constructor.

First, if your constructor simply takes an Analysis2 parameter, that parameter is pass-by-value; the object is always copied. There's no way that the pointer can point to the actual object that was passed in, since your constructor only gets a copy of it. You need to use a reference parameter:

MaxResults(Analysis2& analysis);

Second, you can't directly assign an object to a pointer to that object. You need to use the & operator to take the address of the object.

MaxResults(Analysis2& analysis)
{
    analysis2 = &analysis;
}

On an unrelated note: it's good style to use a member initializer list for the constructor.

MaxResults(Analysis2& analysis)
    : analysis2(&analysis)
{
}
like image 44
John Calsbeek Avatar answered Jan 20 '26 02:01

John Calsbeek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!