0

Why is it that below code is always returning the last player in the array?

The operator bool operator > (Player &P) { return Age > P.Age; }seems not to be working properly. I see it as "compare the age of the element in the left object to the age of the element in the right object". Any suggestions?

Note: I don't intend to use std::vector or std::string.

#include <iostream>
using namespace std;

class Player {
    int Age;
    char *Name;
public:
    Player() {}
    void setName(char *n) { Name = n; }
    void setAge(int a) { Age = a; }
    bool operator > (Player &P) { return Age > P.Age; }
    void showName(){ cout << Name; }
};

int main()
{
    Player *ArrayPlayers = new Player[2];
    ArrayPlayers[0].setName("Player1");
    ArrayPlayers[0].setAge(27);
    ArrayPlayers[1].setName("Player2");
    ArrayPlayers[1].setAge(29);
    ArrayPlayers[2].setName("Player3");
    ArrayPlayers[2].setAge(24);

    Player *Oldest = &ArrayPlayers[0];
    for (int i = 0; i < 3; i++) {
        Player *Current = &ArrayPlayers[i];
        if (Current > Oldest) {
            Oldest = Current;
        }
    }

    cout << "Oldest player is: ";
    Oldest->showName();
    getchar();
}
3
  • 1
    You are comparing pointers. Commented Jan 25, 2015 at 11:47
  • If this is supposed to be C++, you should really drop char pointers and use a string class like std::string. It will resolve 50% of your debugging troubles. Commented Jan 25, 2015 at 11:54
  • You access out of bounds of ArrayPlayers. It has two entries, [0] and [1], however you write to [2] . Commented Jan 25, 2015 at 14:04

1 Answer 1

3

It's because you are comparing pointers (Player*) not Player instances. The simplest fix to achieve the desired result is to dereference:

if (*Current > *Oldest) {

This will invoke your operator> implementation for the Player class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.