Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Whoa there.</p> <p>There's a few problems, <strike>but your segfault is probably because you're passing a <code>char*</code> -- which is just a pointer, and then trying to <code>cout</code> it in <code>disp()</code>. Problem is, that pointer does not live in <code>disp()</code>, it lives in <code>main()</code>. You probably want to either deep-copy the <code>char*</code>, or use <code>std::string</code>. Doing it this way will not work.</strike></p> <p><strong>EDIT</strong>: </p> <p><em>See EDIT 2</em></p> <p>You can not just assign name to the class's <code>name</code> variable. If you do that, you'll get unpredictable results - and you'll probably STILL segfault. Remember: in C/C++, objects are locally scoped unless allocated on the heap. In this case, in your ctor, you'd want to do something like:</p> <pre><code>this-&gt;name = new char[ strlen( name ) + 1 ]; strcpy( this-&gt;name, name ); </code></pre> <p>And in the destructor, you'll want to do something like:</p> <pre><code>delete [] this-&gt;name; </code></pre> <p>Note: my syntax may be completely wrong, and I realize the above code is inherently unsafe as you're not checking the <code>char*</code> to make sure it's not NULL, and you're not checking the return value of <code>new.</code> Nevertheless, this should get you started.</p> <p><strong>EDIT 2:</strong> I stand corrected. String literals are treated as constant storage and thus live on for the duration of the program. <em>Nevertheless</em>, the lesson, I believe, is important: <strong>in general, when not dealing with string literals</strong>, passing a pointer (or array, etc.), you need to allocate storage for it and deep-copy. You also need to de-allocate appropriately when destroying said object.</p>
 

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