I'm trying to compare objects of a common base class together. The comparison should fail (output a failure string, for instance) in any case when the two objects differ in class, or differ in values specific to the object. Ideally the comparison is somehow enforced, such that a new derived class would also have to write a comparison function to members of its class. Here's a code example:
#include <iostream>
#include <string>
#include <vector>
class Vehicle
{
public:
virtual std::string compareTo(Vehicle* v) = 0;
};
class Bicycle : public Vehicle
{
public:
Bicycle() { color_ = "red"; }
std::string compareTo(Vehicle* v) { return "We're different vehicles."; }
std::string compareTo(Bicycle* b) { return color_.compare(b->color_) ? "We're different bicycles." : "We're the same bicycle."; }
private:
std::string color_;
};
class Car : public Vehicle
{
public:
Car() { style_ = "sedan"; }
std::string compareTo(Vehicle* v) { return "We're different vehicles."; }
std::string compareTo(Car* c) { return style_.compare(c->style_) ? "We're different cars." : "We're the same car."; }
private:
std::string style_;
};
int main()
{
Vehicle* compareFrom = new Bicycle();
std::vector<Vehicle*> compareTos;
compareTos.push_back(new Bicycle());
compareTos.push_back(new Car());
std::vector<Vehicle*>::iterator it;
for (it = compareTos.begin(); it != compareTos.end(); ++it)
std::cout << compareFrom->compareTo(*it) << std::endl;
return 0;
}
Currently, the output (which you can see here) says "We're different vehicles". I know this is happening because I'm using the abstract base pointer. The problem is how to fix it!
The output I'd like to have is that the bicycles output that they're the same, because they do have the same color. Bicycles and cars should output that they're different vehicles. Bicycles of different colors and cars of different styles should also output that they're different. I feel like there must be a great pattern to use to solve this problem, but I'm getting mired in dynamic casting or unsafe downcast issues. Also, I would like for the comparison function to be enforced among members of the same class (so Bicycles must be able to compare to other Bicycles).