A class using it's own created objects by function parameters

I was wondering if it's normal to create a function inside a class that uses it's own made objects. For example:

Entity.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
void Entity::playerAttack(Entity &Player, Entity &Enemy) {
    cout << "\nPlayer is Attacking!" << endl;
    cout << "Enemy's health was at: " << Enemy.getHealth() << endl;
    totalHealth = Enemy.getHealth() - Player.getDamage();
    Enemy.setHealth(totalHealth);

    if (Enemy.getHealth() <= 0) {
        Enemy.setHealth(0);
	cout << "\nEnemies is 0 or below" << endl;
	cout << "Players health is at: " << Player.getHealth() << endl;
    } else {
	cout << "Enemies health is now at: " << Enemy.getHealth() << endl;
}


source.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Entity constructE(float damage, float health, float regen) {
    Entity Entity;
    Entity.setDamage(damage);
    Entity.setHealth(health);
    Entity.setRegen(regen);

    return (Entity);
}

void playerAttack(Entity &Player, Entity &Monster) {
    Player.playerAttack(Player, Monster);
}
    
int main() {
    Entity Player = constructE(10, 100, 10);
    Entity Monster = constructE(5, 20, 5);
    playerAttack(Player, Monster);
}


Basically, I'm creating objects from the class "Entity". I then call the function playerAttack(Player, Monster) which puts the created objects back into the class where it came from. Is this by standard the create way of doing it? I started watching C++ videos yesterday and I just took everything I learned and threw it all in so I don't know if it's the "Correct" way of doing things.
Last edited on
Non-static member functions have to be invoked by a calling class object – in your playerAttack() I think this is the role you envisage for the Entity object Player in which case it needs to be moved out of the function's argument list and become this object for invoking playerAttack()

I'm not sure whether of not to suggest also that playerAttack() should be const qualified. I can see Enemy health could certainly change in this method from here:
 
Enemy.setHealth(0);
but there doesn't seem to anything corresponding to this for the object Player which might be revised into this object as discussed previous paragraph

But rather than me going on and on here are two of the foremost gurus of C++ on the topic:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c4-make-a-function-a-member-only-if-it-needs-direct-access-to-the-representation-of-a-class

also couldn't a class ctor overload handle the role of constructE()?
Topic archived. No new replies allowed.