According to cppreference, a trivially copyable class should:
(class) has no virtual member functions;
(class) has no virtual base classes;
I don't understand the reason behind these requirements.
I tried to figure it out myself by doing:
#include <iostream>
struct virt
{
int q;
void virtual virt_func()
{
q += 2;
std::cout << "base implementation: object value " << q << std::endl;
}
};
struct virt_1 : public virt
{
float w;
void virt_func() override
{
w += 2.3;
std::cout << "child 1 implementation: object value " << w << std::endl;
}
};
struct virt_2 : public virt_1
{
double e;
void virt_func() override
{
e += 9.3;
std::cout << "child 2 implementation: object value " << e << std::endl;
}
};
int main()
{
virt_2 * t = new virt_2();
t->virt_func();
void * p = malloc(sizeof(virt_2));
memmove(p, t, sizeof(virt_2));
static_cast<virt_2 *>(p)->virt_func();
std::cout <<"End of a file" << std::endl;
return 0;
}
and it works as it should, by printing:
child 2 implementation: object value 9.3
child 2 implementation: object value 18.6
End of a file
So, why, is what is effectively is a, no vtable pointer requirement is there? I mean, it's a simple pointer that can (should) be copied without any problem at all, right?!