user16155164
user16155164

Reputation:

Return the name of object in method

I'm pretty new to coding, and I'm following this French tutorial that is basically making a RPG game used through console.

So I got a Character class in a .cpp file and .h, another .h .cpp couple of files for the weapons, and my main.

I got a function on my CPP file that's like this :

void Character::attack(Character &target)
{
    target.takeDamage(m_weapon.getDamage());
     
}

So far, in understand I'll use it in this way : davids.attack(goliath) and I made an alias so I can easily use the takeDamage function of my target using its alias.

but I'd like to add a console line like David attacked Goliath and made X damages in that function. And it looks like I can't call another function like

string Character::getname 
{return name}

due to the fact I use 2 different characters.

Is there a way to get around that or should I get them both an alias?

Upvotes: 0

Views: 80

Answers (2)

Balan Narcis
Balan Narcis

Reputation: 139

If C++17 is available to you I recommend using CRTP.

#include <iostream>
#include <string>
#include <string_view>

template <typename Derived>
class Character{
    static constexpr std::string_view CName = "Character";

public:
    constexpr const std::string_view& getName() { return Derived::CName; }

    template<typename K>
    void Attack(Character<K>& Target) {
        std::cout << getName() << " attacked " << Target.getName() << "\n";
    }
};

class David : public Character<David>{
    public:

    static constexpr std::string_view CName = "David";
};

class Goliath : public Character<Goliath>{
    public:
    static constexpr std::string_view CName = "Goliath";
};

int main(int a, char** argv){

    David d;
    Goliath g;

    d.Attack(g);

    return 0;
}

Output: enter image description here

Upvotes: -1

Robert Kwiatkowski
Robert Kwiatkowski

Reputation: 461

Assuming the Character class has field like name you can access the field in your method by using this->name (it will acces name of the object which called the method, in this case it is David) and the target.name will be "Goliath".

Upvotes: 3

Related Questions