Re: operator==
"Fred Zwarts" <F.Zwarts@KVI.nl> writes:
"Andrea Crotti" <andrea.crotti.0@gmail.com> wrote in message news:m11v5k1vak.fsf@ip1-201.halifax.rwth-aachen.de...
Is it possible in theory to force the subclasses to have an operator==?
Now I wanted to define a generic == operator, and supposing Packet is
the superclass and fields:
std::vector<Serializable *> fields;
In serializable I also have defined
virtual bool operator==(const Serializable& other) { return false; }
So here it is
bool Packet::operator==(const Packet& other) const
{
for (size_t i=0; i < fields.size(); ++i) {
if (! ((*fields[i]) == (*other.fields[i]))) {
return false;
}
}
return true;
}
and it doesn't work unfortunately.
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7ba6830 in Packet::operator== (this=0x7fffffffd070, other=...) at src/Packet.cpp:22
22 if (! ((*fields[i]) == (*other.fields[i]))) {
the fields of the other object should be also set to correct memory
addresses, and thus it should be fine.
What could be wrong in this?
Many things could be wrong. In particular in the code that you do not show.
Please, reduce your problem to a small program that exhibits the problem,
that we can compile and try out. Probably, in the process of reducing it, you
will already discover yourself where the problem is located.
Now we have to guess. Probably, one of the pointers in fields is invalid,
but you don't show us how you populate this vector.
Ok I wrote a small example
#include <vector>
class Interface;
class Base
{
protected:
std::vector<Interface *> fields;
public:
Base();
virtual bool operator==(const Base& other) {
for (size_t i=0; i < fields.size(); ++i)
if (! ((*fields[i]) == (*other.fields[i])))
return false;
return true;
}
};
class Interface
{
public:
Interface();
// just an example, should be overloaded of course
virtual bool operator==(const Interface& other) { return false; }
};
class Ext : public Base
{
private:
Interface x;
Interface y;
public:
Ext() {
fields.push_back(&x);
fields.push_back(&y);
}
};
int main() {
return 0;
}
this is basically what I'm doing, and now it doesn't compile though,
because I guess it doesn't find operator== as a possible method of Ext
(even if it's virtual).
Any idea on how to do this?