Need some explanation about a class has a class member

Hi there,
I tried to understand the following code
1
2
3
4
5
6
7
8
9
10
11
12
#include <string>
using namespace std;
class RQ1
{
private:
    string st;       // a string object
public:
    RQ1() : st("") {}
    RQ1(const char * s) : st(s) {}
    ~RQ1() {};
// more stuff
};


I think I am having trouble understanding how st is created and how it gets deleted. can someone help me to sort it out?
my understanding is:
1. When constructing RQ1 using "RQ1 *rqPtr = new RQ1", in the constructor it will allocate a memory space for RQ1 in the heap which contains an address pointing to st constructed in the stack(I assume st will be created in the stack ?) Or st is actually all constructed in the heap?
2. How is the destructor clean up the memory for such member objects? what is the order to delete them, how is the destructor of string gets called in this case?

Thanks for the advice.
1. When constructing RQ1 using "RQ1 *rqPtr = new RQ1", in the constructor it will allocate a memory space for RQ1 in the heap which contains an address pointing to st constructed in the stack(I assume st will be created in the stack ?) Or st is actually all constructed in the heap?


The memory for RQ1 is allocated via new before the constructor of RQ1 is invoked. The variable st, being a member of RQ1, is constructed in the new'd area of memory during the construction of the RQ1 object. strings typically call new themselves (ignoring the possibility of "small string" implementations) for storage of the text they represent. That memory will not be a part of the new'd RQ1 memory space, but will be in a distinct area on the heap.

2. How is the destructor clean up the memory for such member objects? what is the order to delete them, how is the destructor of string gets called in this case?


It would be hard to explain properly speaking only of the destructor. To free and destroy the object allocated by new, one must do a delete (delete rqPtr;). Which invokes the destructor of the object pointed to, and then frees the memory the object was occupying. The destructors of the members are in order of their appearance in the class (which, not coincidentally, also is the order of construction) and are invoked automatically by the compiler. In this example there is no need for a destructor.

If it wasn't clear, the only thing occupying space on the stack in your example is rqPtr.
Last edited on
Topic archived. No new replies allowed.