Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can do what you want with a proxy object:</p> <pre><code>class source_of_B { class B &amp;source; source_of_B(B &amp;source): source(source) {} friend class A; friend class B; }; </code></pre> <p>Because it has no public constructors, creation of such object is restricted to its friends. So you can add public constructor to B that accepts the proxy without compromising your requirement to create B's at controlled locations:</p> <pre><code>class B { int x; B(int x): x(x) {} friend class A; public: B(const source_of_B &amp;arg): x(arg.source.x) {} }; class A { B b; public: A(): b(5) {} source_of_B create_object() { return source_of_B(b); } }; int main() { A a; B b = a.create_object(); } </code></pre> <p>but you can no longer use <code>auto b = a.create_object();</code> with this method.</p> <p><strong>Edit</strong></p> <p>If your compiler supports <a href="http://en.wikipedia.org/wiki/Return_value_optimization" rel="nofollow">return value optimization</a>, which it probably does, you can go without the proxy. Just change <code>create_object()</code> to return <code>B</code> directly:</p> <pre><code> B create_object() { return b; } auto b2 = a.create_object(); </code></pre> <p>The copy constructor will be called by <code>create_object()</code> itself. The only problem would be that some (older) compilers have restrictions on the complexity of the function. See the Wikipedia article for example. Working example is at <a href="http://ideone.com/w1jKAd" rel="nofollow">http://ideone.com/w1jKAd</a>.</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.
    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