How do I calculate the amount of memory a class object uses in C++?
<p>I'd like to calculate the amount of memory in bytes that an object uses. Given</p>

<pre><code>struct A
{
    float data[16];
    int index;
};

struct B
{
    A a;
};
</code></pre>

<p>Is the following the correct way to do this?</p>

<pre><code>template &lt;class Type&gt;
size_t footprint();

template &lt;&gt;
size_t footprint&lt;A&gt;()
{
    return sizeof(float) * 16 + sizeof(int);
}

template &lt;&gt;
size_t footprint&lt;B&gt;()
{
    return footprint&lt;A&gt;();
}
</code></pre>

<p>I'm not sure about footprint() since I've heard that compilers may add extra information just to store member variables, and I'm not sure about footprint() since it refers to a class object. Does that require some memory as well?</p>

<p>EDIT: Okay, say the situation changed such that we're not using a static array but an actual pointer:</p>

<pre><code>#include &lt;iostream&gt;

using namespace std;

struct A
{
    A(int size_)
    {
        data = new float[size_];
        size = size_;
    }

    ~A()
    {
        delete [] data;
    }

    float* data;
    int size;
};

struct B
{
    B() : a(16) {}

    A a;
};

size_t footprint(const A&amp; a)
{
    return sizeof(float) * a.size + sizeof(int);
}

size_t footprint(const B&amp; b)
{
    return footprint(b.a);
}

int main()
{
    A a(16);
    B b;

    cout &lt;&lt; "sizeof(A) = " &lt;&lt; sizeof(A) &lt;&lt; endl;
    cout &lt;&lt; "sizeof(B) = " &lt;&lt; sizeof(B) &lt;&lt; endl;
    cout &lt;&lt; "footprint(a) = " &lt;&lt; footprint(a) &lt;&lt; endl;
    cout &lt;&lt; "footprint(b) = " &lt;&lt; footprint(b) &lt;&lt; endl;
}
</code></pre>

<p>Here you would need to actually have a special sizeof function (here called footprint) right?</p>
