Jump to content
  • Advertisement
Sign in to follow this  
petelta

passing in Class parameters

This topic is 4223 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

is it possible to pass in 2 class paramters to a function. I have a Character class, one is the player, and the other is the enemy. Now I have a battle function, and was wondering if I can pass both character classes into the battle function so I can keep track of there hit points and things like that. What Im thinking is: void battle(character player, character enemy) { player.GetHitPoints(); enemy.GetHitPoints(); } just wondering if something like that is possible.

Share this post


Link to post
Share on other sites
Advertisement
Yes, it is possible. Be warned that in C++, you will require to explicitly pass classes by reference:

void battle(character & player, character & enemy)
{
player.GetHitPoints();
enemy.GetHitPoints();
}

Share this post


Link to post
Share on other sites
[EDIT - Toohrvyk beats me to it (again)[smile]]

Yes. That is, of course, possible.

One thing to bear in mind though, is that if you do it like that, the objects will be copied and you will be working on copies in the function.

You can pass them in by reference instead to avoid the copy:


void f(character &a,character &b)
{
}


That will also mean any changes you make to them in the function will affect the objects outside the function.

If you do not want to be able to change the objects in the function, but want to avoid the copy, pass by const reference:


void f(const character &a,const character &b)
{
}


For small classes that you don't want to modify, passing as you have posted is fine. For anything larger or involving complex copying, either of the above options are worth considering.

HTH

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!