I ran into a weird isue with virtual meshods when i call them from '<' overloaded operator. As you allready know, in order to used the std::set I must to define propper comparision operator into the element class. But in my case this class have few derived forms(There are few diffrent class how inherit from this element base class) So the set may contains elements of diffrents derived types.
The problem comes when I try to using virtual meshods into the operator function's block[I doing this in order to decide which element is greater depend on the derived class type]. When I doing this the base class meshod is called insted of the overriding one!.
I did some debuging work and I found that from some reason the operator functions' arguments sometime lose their orginal derived type.
I would appriciate an explanation why this happening. I'm starting to wonder if the insertion process is copying the elements data into a new ones without the derived type.
This is my code:
#include <set>
#include <string>
class Base
{
public:
std::string name;
public:
Base() { name = "Base"; }
virtual void DummyVirtualFunction() {};//For enable the vtable
};
class Derived : public Base
{
public:
Derived() : Base() { name = "Drived"; }
};
bool operator<(const Base& first, const Base& secound)
{
Base base_instance = Base();
Derived drived_instance = Derived();
long base_vtable = *((long*)&(base_instance)); //The Vtable-Pointer-Value(x64) of Base
long drived_vtable = *((long*)&(drived_instance)); //The Vtable-Pointer-Value(x64) of Derived
long first_vtable = *((long*)&first); //The Vtable-Pointer-Value(x64) of the 'first'
long secound_vtable = *((long*)&secound); //The Vtable-Pointer-Value(x64) of the 'secound'
printf("first's name is '%s' and its have vtable of the %s \n", first.name.c_str(), (first_vtable == base_vtable) ? "Base. WTF!!!" : "Derived.");
printf("secound's name is '%s' and its have vtable of the %s \n", secound.name.c_str(), (secound_vtable == base_vtable) ? "Base. WTF!!!" : "Derived.");
return (void*)&first < (void*)&secound;//Regular pointers comperation
}
void main()
{
std::set<Base> set;
set.insert(Derived());
set.insert(Derived());//The secound insertion calls to the '<' operator in order to arange the set nodes in the right order
}
Sorry about my English.