Home > Software engineering >  Overloading output operator is not working as intended
Overloading output operator is not working as intended

Time:11-25

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);
    }
};

CodePudding user response:

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;
  •  Tags:  
  • c 11
  • Related