Creating class objects on the stack
<p>Do class objects declared on the stack have the same lifetime as other stack variables?</p>

<p>I have this code:</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;vector&gt;
using std::vector;
#include &lt;string&gt;
using std::string;

class Child;
class Parent
{
public:
    Parent(string s) : name(s) { };
    vector&lt;Child&gt; children;
    string name;
};
class Child
{
public:
    Child() { /* I need this for serialization */ };
    Child(Parent *p) : parent(p) { };
    Parent *parent;
};

Parent
family()
{
    Parent p("John Doe");
    int i;
    printf("family:\n\tparent: 0x%x\n\ti: %x\n", &amp;p, &amp;i);
    for (i = 0; i &lt; 2; ++i)
        p.children.push_back(Child(&amp;p));
    return p;
}

int
main(void)
{
    Parent p = family();
    printf("main:\n\tparent: 0x%x\n", &amp;p);
    for (unsigned int i = 0; i &lt; p.children.size(); ++i)
        printf
        (
            "\t\tchild[%d]: parent: 0x%x parent.name '%s'\n", 
            i, 
            p.children[i].parent,
            p.children[i].parent-&gt;name.c_str()
        ); 
    return 0;
}
</code></pre>

<p>My questions:</p>

<ul>
<li>In function <code>family</code>, is <code>Parent p</code> declared on the stack?  From looking at the output, it would seem so</li>
<li>Each created <code>Child</code> goes on the stack too, right?</li>
<li>When I create each <code>Child</code> instance, I pass it a pointer to a stack variable.  I imagine this is a <strong>big no-no</strong>, because stack variables are guaranteed to live only until the end of the function.  After that the stack should get popped and the variables will be destroyed.  Is this correct?</li>
<li><code>vector.push_back()</code> <a href="http://www.cplusplus.com/reference/stl/vector/push_back/" rel="nofollow">passes arguments by reference</a>, so at the end of the <code>family</code> function, <code>p.children</code> just contains references to the local variables, right?</li>
<li>Why is it all working?  In <code>main</code>, why can I access the parent and each of its children?  Is it all because the local variables from <code>family</code> are still intact and haven't been overwritten by some subsequent function call?   </li>
</ul>

<p>I think I'm misunderstanding where stuff lives in memory in C++.  I'd really like to be pointed a resource that explains it well.  Thanks in advance.</p>

<p><strong>EDIT</strong></p>

<p>Output from compiling the source and running:</p>

<pre><code>misha@misha-K42Jr:~/Desktop/stackoverflow$ ./a.out 
family:
    parent: 0x2aa47470
    i: 2aa47438
main:
    parent: 0x2aa47470
        child[0]: parent: 0x2aa47470 parent.name 'John Doe'
        child[1]: parent: 0x2aa47470 parent.name 'John Doe'
</code></pre>
