Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overloading output operator is not working as intended

I’m trying to overload << to print the protected members of a class as a string, but when I try to use it in another class doing std::cout << player2; I get "0x7f60b0100" as output.

"player2" is an Actor*, so I’m not sure what’s happening.

class Actor {

private:
    string type;
protected:
    int health;
    int damage;
    vector<MoveType> moves;

public:
    Actor(string type, int health): type{ type }, health{ health }{damage=0;}
    virtual void Hit(int damage){health = health-damage;}
    virtual void Heal(int amount){health=+amount;}
    const vector<MoveType>& GetMoves() const {return moves;}

    bool IsDead() { return health <= 0; }

    friend ostream& operator<<(ostream& out, const Actor& actor){
        return (out << "DAMAGE DONE: " << actor.damage << "HEALTH: "<< actor.health);
    }
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As you’ve said it’s a pointer to an Actor instance, so that’s what you get printed, the value of this pointer.

You need to derefernce the pointer:

std::cout << *player2;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading