9.2 Methods with Arguments

A method can have one or more arguments. Arguments are used to pass values to a method. In the previous example, the reset() method didn’t need an argument. We know what has to be done to put a circle back in the middle of the screen. But should you write a method to place a circle on any position, you’ld have to pass the desired position as an argument. Like so:

 
class movingCircle { 
  Circle c; 
  Vec2 speed; 
 
5  void setPos(Vec2 pos) { 
    c.pos = pos; 
  } 
} 
 
10// somewhere in your application 
movingCircle mc; 
Vec2 p(0.1, 0.4); 
mc.setPos(p);  

This method has an argument of the type Vec2. The argument is used internally to alter the circle’s position. It is important to remember you only pass the value of the argument, not its name or the variable itself. There is no established relationship between an method and the variables passed into it.

 
movingCircle mc; 
Vec2 p(0.1, 0.4); 
mc.setPos(p);     // pass contents of p to mc 
p.x += 0.1;       // altering p does not alter the position in mc!!! 
5mc.setPos(p);     // call setPos again to pass the new contents to mc  

Exercise
Add the method setPos to your exercise. With it, try something new in the application: every time you press F1, a new random position should be assigned to every circle.

Add a method setRadius with a float argument. This method should change the radius of the circle. Change the radius along with the the position when you press F1. (Remember to use only small values, like a 0.01 to 0.2 range.)