I'm relatively new to C++, and my professor did not go into as much detail into operator overloading as I'd like when I took his class. I'm trying to implement a way to compare objects (using > or <) that all inherit an abstract class, but I'm having trouble with the syntax/logic.
I tried having it be a member of the parent class, but I couldn't figure out how to call a pure virtual function from inside the base class. Then I tried using templates but that's just giving me a headache (my professor didn't go too in-depth on those either).
I'm aware I completely failed in the operator function (and any help with the proper syntax would be appreciated).
#include <iostream>
enum cType { point, maxima, inflection };
class CONSTRAINT {
public:
//coordinates
int x, y;
//gets what type of constraint the object is
virtual cType getType() = 0; //pure virtual
//I'm sure this syntax is horrendous and completely wrong.
//I was just trying to emulate what I found online :(
bool operator > (const CONSTRAINT &rhs) {
//If the constraints have the same type, compare by their x-value
if (getType() == rhs.getType())
return (x > rhs.x);
//Otherwise, it should be point > maxima > inflection
else
return (getType() > rhs.getType());
}
};
class POINT : public CONSTRAINT {
public:
virtual cType getType() { return point; }
};
class MAXIMA : public CONSTRAINT {
public:
virtual cType getType() { return maxima; }
};
//I have another inflection class that follows the pattern
int main() {
POINT point1, point2;
point1.x = 3;
point2.x = 5;
MAXIMA maxima;
maxima.x = 4;
std::cout << (point1 > point2);
std::cout << (point2 > point1);
std::cout << (maxima > point2);
std::cout << (point1 > maxima );
return 0;
}
I would expect: 0110 if the program would compile.
Instead I get the following errors:
"the object has type qualifiers that are not compatible with the member function "CONSTRAINT::getType""
"'cType CONSTRAINT::getType(void)': cannot convert 'this' pointer from 'const CONSTRAINT' to 'CONSTRAINT &'"
Thanks.