0

memory for class object having pointer as data member

Hi A class has char* and int as member variable. Constructor of class allocates memory to char*. Hence , I am de-allocating memory of char* into destructor. This is what a simple class is. Suppose system is 32 bit and hence, I would need 8 byte (4 for int and 4 for pointer) for this class object. Now on this I have below questions: Case 1: If I create a class object in main method, object is stored on stack. But memory required for char* is taken from heap due to new operator....Is this correct? Does this mean that class object takes 8 byte from stack (due to int and pointer) and additional from heap as per input string size? Case 2: If I create a class object pointer in main method, pointer object is stored on stack. But memory required for int and char* is taken from heap....Is this correct? Does this mean that class object pointer takes 4 byte from stack (for class pointer) and additional from heap as per input string size + 8 bytes for data members? Also as pointer is allocated in main using new, I must delete the same in main method even though char* is getting freed by destructor. Many thanks and sorry for such a basic question.

18th Jun 2020, 9:28 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
1 Antwort
+ 1
In my opinion Case 1 yes for both questions Case 2 yes for both questions Finally yes you must deallocate the memory for the class object
18th Jun 2020, 10:22 AM
Anthony Maina
Anthony Maina - avatar