My opinion is that sizeof (type) is preferable to sizeof (variable) in order to avoid ambiguity. The following example shows an instance of a derived class that is referenced by a base class pointer. The size method returns sizeof (Derived), so sz1 == sz3 == sz4. The caller can reasonably expect sizeof (Base) if they have no understanding of the implementation.
class Base
{
public:
virtual size_t size( void )
{
return sizeof( *this ) ;
}
private:
int a ;
double b ;
} ;
class Derived : public Base
{
public:
virtual size_t size( void )
{
return sizeof( *this ) ;
}
private:
long c ;
} ;
int main( int argc , char * argv[] )
{
Base b ;
Derived d ;
size_t sz0 = sizeof( Base ) ;
size_t sz1 = sizeof( Derived ) ;
size_t sz2 = b.size() ;
size_t sz3 = d.size() ;
Base * pb = &d ;
size_t sz4 = pb->size() ;
}
source
share