9.3 More arguments
Methods are not limited to a single argument. You can add more as long as they’re
separated with comma’s.
class movingCircle {
Circle c ;
Vec2 speed;
5 void init(float r, Vec2 pos, Vec2 speed) {
c.r = r ;
c.pos = pos ;
T.speed = speed;
}
10}
// somewhere in your application
movingCircle mc;
Vec2 p(0.1, 0.4);
15mc.init(0.1, p, Vec2(0.3, -0.5));
Again, the example introduces a few new concepts:
-
T
- What if the name of an argument is the same as the name of a class variable?
In the example above there is an argument called ’speed’, but also a
variable called speed. How will the compiler know which is which, when
you just type speed. Well, as a rule the most local declaration is used,
which in this case is the argument. To indicate you want to use the class
variable, you can use T. Again in the example, the value of the argument
’speed’ is passed to the class variable ’speed’.
-
Passing arguments
- When the init method is used, a predefined Vec2 is used
to pass the position. But speed also needs a Vec2. In this case, a new
Vec2 is created directly inside the braces and passed as an argument. Both
options are valid, but the first one is generally used when you still need
the object p after passing it to the function. This would not be possible
with the second Vec2 because it does not have a name.
Exercise
And in init method to your class and use it.