C ++ methods in derived classes with different parameters

This is a question about how to realize some of the needs that I had recently. I am sure that there is a sample or a general solution for this, and although I came with it, I really want to know more.

Suppose I work in a game in which all entities related to the game itself come from the class "Actor" (for example, "obstacle", "moving obstacle", "projectile" and "gun"). In the game, all these objects are stored in the std::vector<Actor *> so that they can pass.

Now suppose that each β€œActor” can β€œdo” something at every step and give them a method of β€œacting”. Obstacle :: act will do little, Moving_obstacle :: act and Projectile :: act will move them, and "Cannon :: act" will create a new shell. It makes sense to have a pure virtual function Actor :: act, so I can, in turn, do something like:

 std::vector<Actor *>::iterator b=myvectorofactors.begin(), e=myvectorofactors.end(); while(b < e) { *b->act(); b++; } 

And let them all "act." Well, so far so good ... The fact is that Cannon :: act can have a different prototype or return value (for example, to store the generated projectile and leter it is pushed into the vector), and this "small" difference breaks it all.

Now I know that from a certain point of view, these method overloads are completely different functions. I also know that you can always plan and work out a problem in advance with sufficient foresight ... Or you can simply deal with the problem.

In this case, I simply used different unique identifiers for each derived class of the Actor and used them to translate to the corresponding class and executed them. I am sure that I will start the same problem again, and I am curious to learn about some entry-level solutions.

Thanks in advance for your time.

+6
source share
2 answers

The beginning of the sound, you swear here:

The fact is that Cannon :: act may have a different prototype or return value (for example, to store the generated projectile and leter to insert it into the vector)

Why? Law is an act. The instance must understand this without any other purpose. You must train him in ctor or other calls before acting. Or should he look around during a call to law.

Consider: even if you magically received a payload for different parameters, in the quote above, how would this be clarified? The challenge is abstract. Even if you infected it with some kind of dynamic_cast, still leave the problem, which gun will receive which parameters?

No, participants must collaborate with each other or use some messaging system (see dispatcher) ...

+3
source

internal variables, that the body of each action is different, and they can use an internal private or inherited variable, so if you can set these variables before calling act, so you do not need to send anything through the parameter to be safe or not complicated

+1
source

Source: https://habr.com/ru/post/947124/


All Articles