Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding error thrown by sizeof(class) usage in C++

When I compile my project in C++, the following error is thrown by MSVC :

error #94: the size of an array must be greater than zero

The error is thrown in the following line on doing sizeof :

if (sizeof (MyNamespace::MyClass) == 60)

MyClass is defined thus :

class MyClass: public ParentClass
{
    public:
        MyClass( void *pCreate, int a, int b, bool c) :
              ParentClass( pCreate, a, b, c ) {}

        virtual inline void myFunc ( ) 
        {
            //something
        }
    private:
        virtual ~MyClass(){};

        /**
        * Copy assignment. Intentionally made private and not implemented to prohibit usage (noncopyable stereotype)
        */
        MyClass& operator=(const MyClass&);
};

Can anyone tell me what might be wrong? Even if sizeof returns zero size, why is it a compiler error?

like image 777
kiki Avatar asked Dec 17 '22 12:12

kiki


1 Answers

This error is caused when you take the sizeof of a class that's only declared at that point. E.g. class MyClass; const size_t error = sizeof(MyClass);.

Note that it doesn't matter whether the class is fully defined later: the definition must precede the sizeof.

like image 159
MSalters Avatar answered Dec 19 '22 02:12

MSalters