1

I am implementing a quick sort algorithm. I have a interface

class Comparable{
public:
    virtual int compareTo(Comparable *c)=0;
};

and now I have a class called ComparableInt, which implements Comparable:

class ComparableInt: public algorithm::Comparable{
public:
    int value;
    int compareTo(Comparable *i) {
        ComparableInt *c = dynamic_cast<ComparableInt*>(i);
        return value - (*c).value;
    };
    ComparableInt(int i):value(i){};
};

My question is, is this the correct way to do it? I was try to implement it like this:

class ComparableInt: public algorithm::Comparable{
public:
    int value;
    int compareTo(ComparableInt *i) {
        return value - (*i).value;
    };
    ComparableInt(int i):value(i){};
};

but it seems that this int compareTo(ComparableInt *i) is not a implemention for virtual int compareTo(Comparable *c), so I have to do a dynamic cast. Seeking for your kind help!

cqing
  • 107
  • 4
  • 1
    The "in the spirit of STL" way to do it would be to take any callable object in the quicksort and just call it with the two elements. – chris Jul 26 '14 at 03:32
  • 2
    Why are you using inheritance to implement sorting? Take a look [here](http://stackoverflow.com/questions/24650626/how-to-implement-classic-sorting-algorithms-in-modern-c) for ideas on how this can be done using templates and standard library algorithms. – Praetorian Jul 26 '14 at 03:37
  • The problem with this design is that you don't really have control that you are comparing things that are really comparable with each other. They should really have the same derived type, not the same interface type. – jxh Jul 26 '14 at 06:08

1 Answers1

0

Try this:

template<typename T>
class Comparable
{
public:
    virtual int compareTo(Comparable<T> *c) = 0;
    virtual T getValue() = 0;
};

class ComparableInt: public algorithm::Comparable<int>
{
public:
    int value;
    int compareTo(Comparable<int> *i)
    {
        return value - i->getValue();
    };
    int getValue() { return value; } 
    ComparableInt(int i):value(i){};
};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • If we are going down the virtual function road, I'd define it as `template class Comparable { public: virtual int compareTo(T *c) = 0; }; class ComparableInt: public algorithm::Comparable { /*...*/ };` – T.C. Jul 26 '14 at 03:41