Hi, Lat us take a class like Code: class A { int *i; char *c; A() { i = (int*) malloc( 50 * sizeof(int)); c = (char*) malloc(100); } }; If we created an object for this class then the size of that object will be 8 bytes... My question is how to know how much memory is the object actually dealing with.. i mean in this case 2pointrs = 8 bytes memory allocated for i = 50 * 4 = 200 bytes for c = 100 bytes In total 308 bytes.. Is there any function we can use to get this 308 as the answer... If we are creating some other objects in this class, then that memory also has to include..
Yes you are right... Only 8 bytes will be.. Code: #include<iostream.h> #include<malloc.h> class A { private: int *i; char *c; public: A() { i = new int[50]; c = new char[100]; } }; int main() { A obj; cout<<sizeof(A)<<endl<<sizeof(obj)<<endl; return 0; } First you have to understand how's sizeof operator works. Actulllay it works at the time of compile time. So it calculates sizes available on compile time ..So it will give 8 bytes on 32-bit machine. As i think you understood.
You can't use sizeof because i and c are dynamically sized and therefore not known until runtime, so you would have to write your own custom size function. If i and c are statically sized then you can use sizeof. Code: class A { private: int ilen,clen; int *i; char *c; public: A(int ni,int nc); int size(); }; A::A(int ni,int nc) { ilen=ni; clen=nc; i = new int[ilen]; c = new char[clen]; } int A::size() { return sizeof(*this)+ilen*sizeof(int)+clen*sizeof(char); } class B { private: int i[10]; char c[10]; public: B(){}; }; void go4e_15856() { A a1(10,10), a2(20,20); printf("Size of a1,a2 is %d,%d\n",a1.size(),a2.size()); B b1; printf("Size of b1 is %d\n",sizeof(b1)); }
Right solution!!! By any way You can'nt overload sizeof operator ..So Your solution is nice one... Better If You will take care of all cases. At any time object size can be increased as it depends on ilen and clen as you have taken variables.. Now you have to make accesors function like upDateiLen() and GetiLen() upDateilen() function should taking care of updated values of ilen means called each time when i = new int[ilen]; called and by Getilen() function het the updated value of ilen var. Do same for clen var also.
By deliverately i have done that...bcoz that's my signature/slogan/etc that no one can comment on that. But i didn't understand what you mean.. By any way all over my English is not so good... Thanks for reminding me to alert about spelling... Thanks a lot..
Thank you ansari.. I really don't know that sizeof() will work at compile time... and thank you xpi0t0s for the solution given.. I thought there may be some pre defined function which can do this for us.. Thank you Shabbir.. so far I didn't heard about Code Blocks IDE... I will look into it...
I thought Code Blocks IDE.. From next time onwards if I am posting code I will fallow the code blocks menctioned...