Note that there are some explanatory texts on larger screens.

plurals
  1. POClass Member Variable not Saving State
    primarykey
    data
    text
    <p>I'm new to C/C++, so people excuse me if this is a noob question.</p> <p>I have a controller class, which has a private member variable which is a <code>vector&lt;Contact&gt; contacts</code>. The class has methods which allow us to change the state of this vector (standard CRUD operations).</p> <p>The class has a public method called <code>get_contacts()</code> which returns this private vector of objects:</p> <pre><code>std::vector&lt;Contact&gt; Contacts_Controller::get_contacts() const { return this-&gt;contacts; } </code></pre> <p>I have a method which adds the <code>contact</code> to this private vector via <code>push_back()</code>. The issue is that if the <code>add_contact()</code> method uses the accessor method, then the class variable does not get updated:</p> <pre><code>void Contacts_Controller::add_contact(const Contact &amp;contact) { this-&gt;get_contacts().push_back(contact); } </code></pre> <p>I <em>assume</em> this is a memory issue, perhaps I have some issues with my use of <code>const</code> or I'm not correctly using references, because the following code works exactly as expected:</p> <pre><code>void Contacts_Controller::add_contact(const Contact &amp;contact) { this-&gt;contacts.push_back(contact); } </code></pre> <p>Using either method won't return any errors, but if I then request the vector of contacts after using the first method it'll be empty, whereas the second method correctly adds data to the vector.</p> <p>Again, sorry if this is a noob question, but I'm completely stumped, and I wouldn't know what to search for! How would I fix this referencing issue?</p>
    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.
 

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