Strange Syntax/Question

Hello all,

Here are the functions for a clone of the pong game. I am hoping that someone can help me in knowing why the programmer used parentheses around the keyword int. Also, are the parentheses even needed in this case? This is the first time that I have seen this done and I am just curious as to the why and the how it works. The function is as follows:

1
2
3
4
5
6
7
8
9
int Ball::getX()
{
   return (int) x;
}

int Ball::getY()
{
   return (int) y;
}


The functions were wrote for a class named Ball and the variables x and y are being used for the location of the ball on a coordinate plane. Any and all help is appreciated. Thank you for your time.
you could get away with out them. Since by default it would cast it while returning. But the x and y locations are floating point values. You are trying to return an int so you must cast it. Basically they chose the c-style cast. There are a few other casts. I would probably just do static_cast<int>(x)

http://www.cplusplus.com/doc/tutorial/typecasting/
Last edited on
That is known as C-style type casting. The variables x and y might not be of the int type, which is why they were cast. There are more safer ways to do this in C++, such as static_cast<int>(x). However, it would probably be better to look for a way to avoid having to cast like this, such as having a uniform type for x, y, and what the interface presents.
Thank you. That makes a lot more sense now. I've just never seen type casting done this way before. I've only seen it done with using static_cast. Thanks!
Topic archived. No new replies allowed.