Oops slight correction I made some grave errors I was a bit too generous in my math :)
corrections
10 x sizeof(int) + 20 x sizeof(int) + overhead
should be
sizeof(int) + sizeof(int) + overhead
10 instances of x and 10 instances of y which is total 80 bytes.
should be
1 instance of x and one instance of y = 8 bytes not 80 bytes
From: "Steve Obbayi" <steve@sobbayi.com>
To: "Skunkworks Mailing List" <skunkworks@lists.my.co.ke>
Sent: Monday, November 28, 2011 11:49:34 AM
Subject: Re: [Skunkworks] Size of an object in memory at runtime
In C++ to determine the size of a class in memory you look at the variables linked to the class
so take for example:
class myClass
{
int x = 2;
int y = 3;
const int z = 10;
myClass(int a, int b)
{
x = a;
y = b;
}
int addInt()
{
return x+y;
}
}
The size of this class instance in memory is basically the size of the
two variables x and y which would be about 8 bytes total plus some
overhead which could be a single byte.
Notice the constant int z. This is not part of the instance of a C++
class. Reasoning is even if you make ten instances of the class all you
will have is
10 instances of x and 10 instances of y which is total 80 bytes. z will
only be one instance. Thats why you can use z without creating an object
of the class.
The object is stored in the heap with the values and the pointer to that object is stored in the stack eg
MyClass happy = new MyClass(10, 20);
happy is the address of "new MyClass(10, 20)" is stored in the stack and takes up 1 byte (lets assume the underlying pointer is stored in a single byte)
"MyClass(10, 20)" is stored in the heap and takes up 10 x sizeof(int) + 20 x sizeof(int) + overhead.
There is an argument about the memory of member functions. They behave the same way. calculate the size of the local variables in the member functions. Stuff like for loops, while, if else. those are language constructs and are handled internally by the language hence the overhead.
It is slightly more complicate than this but I hope you get the idea behind memory management in C++ and C also (structs and unions)
Steve
_______________________________________________
Skunkworks mailing list
Skunkworks@lists.my.co.ke