op.14049 op.14049 - 3 days ago 5
C++ Question

How to make Comparable Class in C++

I want to make an interface in C++.
How can I get op2.radius value in operator overloading statement?
I'd like that Comparable Class can be used for others such as Rectangle, Line etc.

#include <iostream>
using namespace std;

class Comparable {
public:
virtual bool operator > (Comparable& op2)=0;
//virtual bool operator < (Comparable& op2)=0;
//virtual bool operator == (Comparable& op2)=0;
};

class Circle : public Comparable {
int radius;
public:
Circle(int radius=1) { this->radius = radius; }
int getRadius() { return radius; }
bool operator > (Comparable& op2)
{
if (radius > op2.radius) // <-- here!
return true;
else
return false;
}

};

template <class T>
T bigger(T a, T b){
if (a > b) return a;
else
return b;
}

void main()
{
Circle waffle(10), pizza(20), y;
y = bigger(waffle, pizza);
cout << "the bigger one is " << y.getRadius() << endl;
}

Answer

You need to do a downcast, there is no generic way to get the radius.
If you are sure the only object passed to it will be of type Circle, then a static cast would suffice.
If that is not the case then try to use a dynamic_cast to check if it is a Circle object. If it fails then just return false.
Note: dynamic_cast would slow down the performance.

bool operator > (Comparable& op2)
{
    Circle* foo = dynamic_cast<Circle*>(&op2);
    if (foo && (radius > foo->getRadius()))
    {
        return true;
    }
    else
    {
        return false;
    }
}
Comments