Note that there are some explanatory texts on larger screens.

plurals
  1. POAccess C++ class member object, but do not allow to override it
    primarykey
    data
    text
    <p>I'm learning C++ and i just have a small problem. I have a class which contains a <code>vector&lt;int&gt;</code>. From outside this <code>vector&lt;int&gt;</code> should be accessable, so it should be possible to add/remove/get its elements.</p> <p>It should not be possible to override the object with a new instance. Here is such an example class (it's minimalized):</p> <pre><code>class MyClass { public: vector&lt;int&gt;&amp; vec() { return _vec; } private: vector&lt;int&gt; _vec; }; </code></pre> <p>E.g. the following code works:</p> <pre><code>MyClass x; x.vec().push_back(0); x.vec().push_back(7); x.vec().push_back(9); cout &lt;&lt; c.vec().size() &lt;&lt; endl; </code></pre> <p>But unfortunately the following code also works:</p> <pre><code>MyClass x; x.vec() = vector&lt;int&gt;(); </code></pre> <p>I like to disallow this, but i did only find the solution to return a pointer of type <code>vector&lt;int&gt; *</code>. But i learned pointers are 'evil' and i shouldn't use them directly, i have to use smart pointers. I think for this problem a smart pointer is useless, so i don't know how to solve this simple problem:-/</p> <p>Or is just a simple pointer the cleanest solution?</p> <p>best regards</p> <p>Kevin</p> <p>-edit-</p> <p>In general i like to make something that can be used like the follwing C# class:</p> <pre><code>public class MyClass { public List&lt;int&gt; List { get; private set; } public MyClass() { List = new List&lt;int&gt;(); } } </code></pre> <p>It's just an example and i just thought about how to make this in C++. Maybe i some cases i have much more complex classes than <code>vector&lt;int&gt;</code>/<code>List&lt;int&gt;</code> to include into other classes.</p> <p>But maybe it is only possible to do this by defining own methods (=interface) to the internal object.</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