Are you asking how you can change the behaviour of Spriteclass, without changing Spriteclass? It's impossible to change behaviour without changing Spriteclass in some way.
You could add a std::function member variable to Spriteclass. For one instance, you set it to some movement function, and for another instance you set it to some generation function.
This is a nasty antipattern, though.
You could give Spriteclass a value indicating what kind of thing it was; an apple or a player, and then have a function to call that changes its behaviour depending on what that value is set to. That's also truly hideous.
The C++ way to have different objects behave differently is for them to actually be different.
If you're only going to have one player, and one apple, then the function doesn't need to be a class function. You could just write your generation function and your movement function as free functions and just call them.
> Is it possible to solve this without creating a new classes?
Yes. Write two non-member functions:
void move( SpriteClass& player ) ;
void generate( SpriteClass& apple ) ;
And then, pass the player object to the first function and the apple object to the second.
Note that the behaviour of an object is more than what appears at first sight by just looking at the member functions of its associated class. For instance, std::cout << str ; is a definite part of the behaviour of the object of type std::string
This is sound advice:
If you're writing a function that can be implemented as either a member or as a non-friend non-member, you should prefer to implement it as a non-member function. That decision increases class encapsulation. When you think encapsulation, you should think non-member functions. - Scott Meyers in Dr. Dobb's
@Repeater && @JLBorges
You both have right. l think the best solution is to create independient functions and to pass each
Because imagine apple object can move for itself. but player object can only move when l press the correponding keys. So it will look pretty ugly to put two movement() methods, and generation() in Sprite class. because player never will call generation method
Sorry l forgot to say l'll have one (controllable) player, and one apple. generates when the player touches.