During job interview, I've been overwhelmed by this question:
bool Res - what it shows to us?
template <class T>
class R
{
class A: public T {
virtual ~A(){}
};
public:
static const bool Res = sizeof(A) == sizeof(T);
};
During my investigation - I've always had sizeof(T) == 1, while sizeof(A) varies. Explanation will be very appreciated.
The value of Res should indicate whether T has any virtual function although there is no such guarantee in the C++ standard:
T does have a virtual function, A doesn't add anything to the representation and can be the same size as T.T does not have a virtual function, A probably adds something to deal with the dynamic dispatch (typically a pointer to something like a virtual function pointer table) and has a different size.The C++ standard doesn't mandate how to dynamic dispatch is implemented and an implementation could be able to some determine from the address what type an object has. In practice all implementations do use a pointer to dynamic type information.
An interesting question is whether a compiler could detect that R<T>::A; can't be used to be inherited from and, thus, decide that it doesn't actually need a virtual function pointer anyway. I'm pretty sure a compiler could do so making the value of R<T>::Res even more questionable.
If T is polymorphic class (has virtual destructor or any virtual method), the size should be the same.
If T is not polymorphic (doesn't have any virtual methods), the size of A is bigger by a pointer to virtual function table.
EDIT. Further explanation: If a class has any virtual method (it means it is designed for being used polymorphically), it has to have a pointer to a virtual function table, which is used to determine which method exactly should be used when a virtual method is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With