Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why size of char is 4 bytes in memory and empty class is 1 byte

Tags:

c++

memory

class

Good time of day!

I wrote some code, but I cannot understand some strange memory anomalies. Could anybody, who has a proper knowledge in class memory using give me a explanation?

My code:

#include <iostream>

using namespace std;

class O
{
    O();
    ~O();
};

class A
{
public:
    A();
    ~A();
    void someFunc();
private:
    int m_a;
};

class B: public A
{
public:
    B();
    virtual ~B();
private:
    int m_b;
};

class C: public B
{
public:
    C();
    ~C();
private:
    char m_c;
};

int main()
{
    cout << sizeof(char) << endl;
    cout << sizeof(int) << endl;
    cout << sizeof(O) << endl;
    cout << sizeof(A) << endl;
    cout << sizeof(B) << endl;
    cout << sizeof(C) << endl;
    cin.get();
    return 0;
}

output:

1  //normal for char
4  //normal for int on x32
1  //why empty class occupies 1 byte?
4  //int m_a.  Where is 1 byte?
12 //4B virtual function, 8B - m_a and m_b.
16 //char needs 1 byte. Why it gets 3 more?

Thank you for attention and answers )

like image 207
Fairyteller Avatar asked Oct 23 '25 18:10

Fairyteller


2 Answers

  • Empty class: Every complete object must have a unique address. Consider EmptyClass a[10], and the fact that array elements are complete objects, and consider how pointer arithmetic works.

  • int m_a? Your assumption is unwarranted. There's no need for an extra dummy byte if you already have meaningful bytes.

  • C: Padding. Again, consider arrays and alignment. Class C will have the alignment of int, and every array member of C a[10] must be aligned, and array members must be contiguous.

like image 184
Kerrek SB Avatar answered Oct 26 '25 08:10

Kerrek SB


O (Empty Class): In order to address the class, it has to have at least 1 byte of space allocated to it. You cannot address anything smaller than a byte.

A (Class with single int member): Its members add up to a single integer's worth of space. That is all it needs and there are no alignment issues.

B (Decrived class with another int member and a vtable): It's space requirement will be determined by both the 2 ints and the vtable. Hence the extra 4 bytes (pointer to the vtable on a 32bit machine).

'C' (Derived class with another char): It has all the stuff from B, and 1 byte (the char), plus 3 more to make it align properly.

like image 40
Zac Howland Avatar answered Oct 26 '25 07:10

Zac Howland