Yang
Yang

Reputation: 9952

C++ pass by pointer

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.

Upvotes: 1

Views: 2828

Answers (2)

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.

Upvotes: 4

Steve Townsend
Steve Townsend

Reputation: 54148

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.

Upvotes: 3

Related Questions