Empty Class Size



  • @class EmptyClass
    {
    public:
    };

    int size = sizeof(a);
    cout<<size<<endl;@

    Output is showing 8. Please tell me why?

    Edit: please wrap code between @ tags. Also moved to C++ gurus; Andre


  • Moderators

    welcome to devnet

    This is a more general question and not related to Qt.
    The best thing is to ask Mr Google "Your text to link here...":http://lmgtfy.com/?q=size+empty+cpp+class

    Plenty of answers already available. Some claim that is has to be at least one byte. So there might be also a compiler dependent flavor in there.

    Also "Bjarne Stroustrup's C++ Style and Technique FAQ":http://www.stroustrup.com/#sizeof-empty might help you


  • Moderators

    Also - 8 is pretty big, so you're probably in a debug build?



  • Yes.

    Microsoft visual studio sizeof(emptyclass) is returning 1. QT compiler why it is returing 8?


  • Moderators

    There's no such thing as a "Qt compiler" (btw. it's Qt, QT is Apple's QuickTime).
    Do you mean MinGW that is bundled with 5.0.1 or Visual C++ compiler when compiling from Qt Creator or are you using some other configuration?

    AFAIK MinGW and VC in both release and debug mode return 1, so what exactly is your config and what is "a" in your example because you're asking very general question with no details at all?



  • bq. Output is showing 8. Please tell me why?

    Distinct objects must have distinct addresses and the standard mandates that sizeof() must return 1 or more in this case to ensure that. Exactly what a compiler returns will depend what else it may have placed in the object (RTTI or debug information for example) and whether the machine architecture requires byte alignment etc. Compilers are free to insert and remove padding bytes as required for their target architecture. It would be an unwise strategy to program assuming that the internal layout or size of an object was fixed between compiler, platform etc.

    GCC 4.6.3 on a 64-bit Linux box returns sizeof(EmptyClass) == 1 for a release/debug build in 64 or 32-bit mode.

    I am going to guess, because you did not say, that "a" is not an instance of EmptyClass but a pointer to EmptyClass. The size of a pointer in a 64-bit environment is typically 64-bit (8 bytes).


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.