Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sizeof of derived class with virtual destructor

Tags:

c++

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.

like image 714
Starl1ght Avatar asked Dec 07 '25 07:12

Starl1ght


2 Answers

The value of Res should indicate whether T has any virtual function although there is no such guarantee in the C++ standard:

  • If T does have a virtual function, A doesn't add anything to the representation and can be the same size as T.
  • If 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.

like image 97
Dietmar Kühl Avatar answered Dec 08 '25 21:12

Dietmar Kühl


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.

like image 36
Estiny Avatar answered Dec 08 '25 21:12

Estiny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!