Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to pass parameters correctly?
    primarykey
    data
    text
    <p>I am a C++ beginner but not a programming beginner. I'm trying to learn C++(c++11) and it's kinda unclear for me the most important thing: passing parameters.</p> <p>I considered these simple examples:</p> <ul> <li><p>A class that has all its members primitive types:<br> <code>CreditCard(std::string number, int expMonth, int expYear,int pin):number(number), expMonth(expMonth), expYear(expYear), pin(pin)</code></p></li> <li><p>A class that has as members primitive types + 1 complex type:<br> <code>Account(std::string number, float amount, CreditCard creditCard) : number(number), amount(amount), creditCard(creditCard)</code></p></li> <li><p>A class that has as members primitive types + 1 collection of some complex type: <code>Client(std::string firstName, std::string lastName, std::vector&lt;Account&gt; accounts):firstName(firstName), lastName(lastName), accounts(accounts)</code></p></li> </ul> <p>When I create an account, I do this: </p> <pre><code> CreditCard cc("12345",2,2015,1001); Account acc("asdasd",345, cc); </code></pre> <p>Obviously the credit card will be copied twice in this scenario. If I rewrite that constructor as</p> <pre><code>Account(std::string number, float amount, CreditCard&amp; creditCard) : number(number) , amount(amount) , creditCard(creditCard) </code></pre> <p>there will be one copy. If I rewrite it as</p> <pre><code>Account(std::string number, float amount, CreditCard&amp;&amp; creditCard) : number(number) , amount(amount) , creditCard(std::forward&lt;CreditCard&gt;(creditCard)) </code></pre> <p>There will be 2 moves and no copy.</p> <p>I think sometimes you may want to copy some parameter, sometimes you don't want to copy when you create that object.<br> I come from C# and, being used to references, it's a bit strange to me and I think there should be 2 overloads for each parameter but I know I am wrong.<br> Are there any best practices of how to send parameters in C++ because I really find it, let's say, not trivial. How would you handle my examples presented above?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    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