Monday, 10 January 2011

Virtual sizeof Do you ever wish you could do this:

Virtual sizeof

Do you ever wish you could do this:
class Base
{
};

class Derived: public Base
{
int x;
};

Base *p = new Derived;

size_t s = sizeof(*p); // s is sizeof(Derived)
Of course it doesn't work because s becomes the size of Base rather than Derived. What you really want is a kind of "virtual sizeof". This is what I came up with:
class Base
{
public:
virtual size_t Size() const = 0;
};

class Derived: public Base
{
int x;
};

template <>
class Wrapper: public T
{
public
virtual size_t Size() const
{
return sizeof(T);
}
};

template <>
T *New()
{
return new Wrapper<>;
}

Base *p = New();

size_t s = p->Size(); // works as desired

No comments:

Post a Comment