tags:

views:

121

answers:

2

hello, guys, i am very new to c++. i have just wrote this class:

class planet
{
public:
 float angularSpeed;
 float angle;
};

here is a function trying to modify the angle of the object:

void foo(planet* p) {
p->angle = p->angle + p->angularSpeed;
}

planet* bar = new planet();
bar->angularSpeed=1;
bar->angle=2;
foo(bar);

It seem that the angle in bar didn't change at all.

+3  A: 

Note that you are passing bar by pointer, not by reference. Pass-by-reference would look like this:

void foo(planet& p)  // note: & instead of *
{
    p.angle += p.angularSpeed;   // note: . instead of ->
}

Pass-by-reference has the added benefit that p cannot be a null reference. Therefore, your function can no longer cause any null dereferencing error.

Second, and that's a detail, if your planet contains only public member variables, you could just as well declare it struct (where the default accessibility is public).

PS: As far as I can see it, your code should work; at least the parts you showed us.

stakx
That's not how you do a reference in standard C++. Well, after your ninja edit it is.
Ben Voigt
@Ben - what's the error here? TIA
Steve Townsend
At the time of my comment, your code was `void foo(planet% p)`. Your ninja-d version is correct.
Ben Voigt
That's a relief. I was expecting a cascading -1 to my own answer, and imminent insanity
Steve Townsend
A typo, I guess. In my keyboard both symbols are close.
gpeche
stakx
@stakx - Yep, StackOverflow is a harsh mistress for the occasionally fat-fingered (slef inclufed)
Steve Townsend
I'm fairly sure the comment also had a `%`, which makes fat-fingering somewhat less likely. Perhaps `/clr` was in effect when stakx got up this morning?
Ben Voigt
_@Ben_: Nah, I've never actually used C++/CLI. The comment didn't have a `%`, but my original answer *did*. Never mind -- it was a very simple typo, due to my writing on a tiny netbook at the moment.
stakx
Ok, just that fact that `%` would have been valid in C++/CLI made me wonder.
Ben Voigt
@stakx - +1 to your comment, for not using C++/CLI, ever.
Steve Townsend
+3  A: 

Appearances must be deceptive because the code should result in foo(bar) changing the contents of the angle field.

btw this is not passing by reference, this is passing by pointer. Could you change the title?

Passing by reference (better) would be

void foo(planet& p) {
p.angle += p.angularSpeed;
}

planet bar;
bar.angularSpeed=1;
bar.angle=2;
foo(bar);

You might also consider a constructor for planet that takes as parameters the initial values of angle and angularSpeed, and define a default constructor that sets them both to 0. Otherwise you have a bug farm in the making due to unset values in planet instances.

Steve Townsend