How to access info from an instance from another instance in c++?

I am just started learning OOP concepts and to help myself learning, I have created a Characters class. From this class I have made instance called main and an instance called monster. Here is the code for the class:

#include <iostream>
#include <string>

using namespace std;
class Character {

public:
string name;
float health;
int attackLevel;
int defenseLevel;

void setAttr(string sName,float sHealth, int sAttackLevel, int sDefenseLevel)  {
    name = sName;
    health = sHealth;
    attackLevel = sAttackLevel;
    defenseLevel = sDefenseLevel;

}



void attack(int whatInstanceToAttack)  {

    whatInstanceToAttack.hitpoints -= 20;  //obviously not valid but how do i do this?

    return whatInstanceToAttack;
}
int defend(string defend)  {

    int damageRelieved = defenseLevel * 2;
    return damageRelieved;
}




};
int main() {
Character main;
Character monster;
main.setAttr("Rafael",200,100,30);
monster.setAttr("Monster1",30,40,30);
cout << "Default Values for Raf are;" << endl;
cout << main.name << endl;
cout << main.health<< endl;
cout << main.attackLevel << endl;
cout << main.defenseLevel << endl;


cout << "Default values for monster are" << endl;
cout <<monster.name << endl;
cout <<monster.health << endl;
cout << monster.attackLevel<< endl;
cout << monster.defenseLevel << endl;



return 0;
}

Basically what I want to do is somehow access the monster instance via the main instance. I want to do this by running the attack method. So if I run

main.attack(monster);

then I want the monster to lose 20 hitpoints.

How do I go about doing this?


Source: oop

Leave a Reply