Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The constructor argument <code>o</code> is a <em>copy</em> of the <code>Object1</code> instance you passed in (since it's being passed <em>by value</em>. In your constructor, when you set your member pointer to its address, that address is the stack frame, which will be invalid after your constructor returns.</p> <p>Here's another way to do this (there are other ways, of course):</p> <pre><code>class Object1 : BaseClass { BaseClass *link; int i; public: // - Prefer initialization to assignment // - Initialize ALL of your members Object1(int a) : link(NULL), i(a) {} // This instance assumes ownership of p Object1(int a, Object1 *p) : link(p), i(a) {} ~Object1() { delete link; } }; int main() { Object1 a(1, new Object1(2)); ... } </code></pre> <p>EDIT: Hmmmm, the only way I can see for you to use the chaining design you have is something ugly like this:</p> <pre><code>class Object1 : BaseClass { BaseClass *link; int i; public: Object1(int a) : link(NULL), i(a) {} Object1(int a, const Object1&amp; o) : link(new Object1(o)), i(a) {} // Copy constructor Object1(const Object1&amp; other) : link(NULL), i(other.a) { // Deep copy linked object if (other.link != NULL) { link = new Object1(*other.link); } } // Assignment operator that does deep copy const Object1&amp; operator=(const Object1&amp; that) { // Check for assignment to self if (this != &amp;that) { delete this.link; this.link = NULL; // Deep copy linked object if (that.link != NULL) { this.link = new Object1(*that.link); } this.i = that.i; } } ~Object1() { delete link; } }; int main() { Object1 a(1, new Object1(2)); ... } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload