Tuesday, October 23, 2012

Question 3: Predict the output, Assuming 32 bit environment
    int takes 4 bytes
    char take 1 byte

    class DemoClass
    {
    private:
        int m_data;
        char m_char;
        char m_otherChar;
        int m_otherData;
    };

    int main()
    {
        std::cout<<"Size of DemoClass : "<<sizeof(DemoClass);
    }



    Options:

    a)     10

    b)    12

    c)     16

    d)    None of the above.



    Answer: b

2 comments:

  1. This happens because of data padding .
    The size of a class object may vary because of any of the following reasons :

    1. Size of all non-static data members
    2. Order of data members
    3. Byte alignment or byte padding
    4. Size of its immediate base class
    5. The existence of virtual function(s) (Dynamic
    polymorphism using virtual functions).
    6. Compiler being used
    7. Mode of inheritance (virtual inheritance)

    ReplyDelete
    Replies
    1. Thanks Kaustabh for your valuable comments.

      Delete