class and inheritance beginner help

I can't even begin to understand the following question. Any help clarify the question would be gr8. question is:

Implement a sort function that takes a vector of pointers to an interface class, Comparable,that defines a method, compare(Comparable& other), and returns 0 if the objects are the same, 1 if the object is greater than other, and -1 if the object is less than other. Create a class that implements this interface, create several instances*, and sort them. If you're looking for some inspiration for what to create—try a HighScoreElement class that has a name and a score, and sorts so that the top scores are first, but if two scores are the same, they are sorted next by name.

Q. how to compare two objects? and what is meant by instances*?
Implement a sort function that takes a vector of pointers to an interface class, Comparable

So you're writing a function called sort(). It takes one parameter: a vector of pointers to class Comparable

that defines a method, compare(Comparable& other), and returns 0 if the objects are the same, 1 if the object is greater than other, and -1 if the object is less than other.

So class Comparable has a method called compare(). It takes one parameter as shown above, and returns an integer. Note that this method should be virtual, or probably pure virtual.

If you're looking for some inspiration for what to create—try a HighScoreElement class that has a name and a score, and sorts so that the top scores are first, but if two scores are the same, they are sorted next by name.


So HighScoreElement is derived from Comparable. It contains a name and a score, and of course a compare() method:

1
2
3
4
5
6
class HighScoreElement: public Comparable {
public:
    std::string name;
    int score;
    int compare(Comparable &other);
};


The compare method should only be called with another HighScoreElement object. To compare the elements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int HighScoreElement::compare(Comparable &other)
{
    HighScoreElement &rhs (static_cast<HighScoreElement &)(other));  // right hand side

    // compare the scores first
    if (score < rhs.score) return -1;
    if (score > rhs.score) return 1;

    // scores are equal. Compare the names
    if (name < rhs.name) return -1;
    if (name > rhs.name) return 1;

    // score and name are equal
    return 0;
}


Topic archived. No new replies allowed.