class animal
{
public: bool is_male; longdouble strength;
};
class fish : public animal{};
class bear : public animal{};
Later in the file, I created this:
1 2 3
animal * river[_river];
river[0] = new fish;
river[1] = new bear;
I need to find something that would allow me to compare river[0] and river[1] and, in this particular example, yield a falsehood since river[0] is a fish and river[1] is a bear. Is there anything I could do?
#include <iostream>
#include <typeinfo>
class animal
{
public: bool is_male; longdouble strength;
virtualinlinebooloperator==(const animal& other)
{
std::cout << "compa" << ' ';
return (typeid(*this) == typeid(other));
}
};
class fish : public animal{};
class bear : public animal{};
int main()
{
animal * river[2];
river[0] = new fish;
river[1] = new bear;
std::cout << (1 == 2) << '\n';
std::cout << (*river[0] == *river[0]) << '\n';
std::cout << (*river[0] == *river[1]) << '\n';
std::cout << (*river[1] == *river[0]) << '\n';
std::cout << (*river[1] == *river[1]) << '\n';
}
There's something about what you're trying to do here that just feels wrong, though. Feels like you're not working with the language. What's you actual design aim here? Maybe there's a better, more axiomatic C++ way to do it.
The program seems to do what I want it to. Can you explain why I need to state "virtual inline" before the comparison operator declaration to achieve the result?
The class needs to be polymorphic - at least one virtual function - in order for this to work. It's not that the comparison operator itself needs to be virtual; that was just convenient. This also works:
#include <iostream>
#include <typeinfo>
class animal
{
public: bool is_male; longdouble strength;
virtualvoid dummy(){};
inlinebooloperator==(const animal& other)
{
std::cout << "compa" << ' ';
return (typeid(*this) == typeid(other));
}
};
class fish : public animal{};
class bear : public animal{};
int main()
{
animal * river[2];
river[0] = new fish;
river[1] = new bear;
std::cout << (1 == 2) << '\n';
std::cout << (*river[0] == *river[0]) << '\n';
std::cout << (*river[0] == *river[1]) << '\n';
std::cout << (*river[1] == *river[0]) << '\n';
std::cout << (*river[1] == *river[1]) << '\n';
}
but if the dummy function has its virtual qualifier removed, it stops working. What the exact method of calculating what type a polymorhpic object is, I couldn't tell you (and I believe it's implementation dependent), but I believe that the vtable is part of it, so a vtable is necessary, and having a virtual function gets us that vtable.