
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 ----- Original Message ----- | From: "aki" <aki275@gmail.com> | To: "Skunkworks Mailing List" <skunkworks@lists.my.co.ke> | Sent: Monday, November 28, 2011 11:13:07 AM | Subject: Re: [Skunkworks] Size of an object in memory at runtime | @James, a very nice question. When I was reading into OOP in C#, this | was my primary concern for many months as they get stored in the | heap. Variables, arrays etc holds much less in the stack, but then | also learnt that memory these days does not cost the price of a | computer as the early days so it was not a major issue. However, I | once did see a single program take up 100% of the memory, yet the OS | was only taking up less than 15% due to the nature of GUI and I | refused to purchase the software. My apprentice view. :-) | On Mon, Nov 28, 2011 at 10:56 AM, James Nzomo < kazikubwa@gmail.com > | wrote: | _______________________________________________ | Skunkworks mailing list | Skunkworks@lists.my.co.ke