In my game I have a Projectile class that initially spawns on the right side of the screen either high or low (randomly chosen in the constructor). The Projectile automatically moves to the left side of the screen, and when it leaves the left side of the screen I want to redefine the existing variable with a new Projectile created by the constructor. However, I can’t seem to get this working. I’ve tried defining it as Projectile *projectile but then my code throws the “expression must have a class type” error. How can I redefine it like
if (projectile.getX()<=0)
projectile = new Projectile();
else
(projectile.move(x--, y)
I have the movement and rendering code working as expected, but right now the Projectile goes across the screen once and disappears.
The problem with the line
projectile = new Projectile()is that the return valued from the expressionnew Projectile()is aProjectile*, not aProjectileobject. You’re then trying to assign it to a Projectile object and that isn’t going to work.You should be able to get the code compiling by replacing that line with
projectile = Projectile()if you don’t want to convert the code to use pointers. Another option would be to add a member function that resets a Projectile object to its default state. The latter can be very beneficial if a Projectile object is expensive to construct and copy.