Thank you Andy and Seeplus for your help.
My question may not be very clear, because it did not get answered yet.
My question is, on the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
duplicate_constref(const int& a, const int& b, const int& c)
//here const with int and ampersand
{
cout << '\n';
cout << "duplicate_constamp (const int& a,const int& b,const int& c):" << '\n';
cout
<< "a*2= " << a * 2 << '\n'
<< "b*2= " << b * 2 << '\n'
<< "c*2= " << c * 2 << '\n';
/*
a=a*2;
b=b*2;
c=c*2;
*/
//i need to comment that out because otherwise the program does not compile
}
void x::duplicate_const(const int a, const int b, const int c)
//here is the same, without the reference
{
cout << '\n';
cout << "duplicate_const (const int a,const int b,const int c):" << '\n';
cout << "a*2= " << a * 2 << '\n';
cout << "b*2= " << b * 2 << '\n';
cout << "c*2= " << c * 2 << '\n';
/*
a=a*2;
b=b*2;
c=c*2;
*/
//and i cannot assign it here either
}
|
duplicate_constref passes a variable by "const reference" and duplicate_const passes a value by "const value".
Keskiverto and Seeplus said that using "const reference" does not create a copy and "const value" does create a copy.
1 Where could one see a "copy" if one uses "const value" ?
I do not understand why a copy would be needed if the value in the end will not change because the "const" is there.
I just want to understand why the professor uses const reference and not just const (I do not understand why he would need to put const
reference if he is not using super big variables like a vector of vectors, like Keskiverto said).
2 Does he need to write on the above code "const reference" or it is a waste of time that gives no changes and one could simply write "const value" and have the same result?
3 Would have the above example any significant change if we as students use "const value" and not "const reference"? Or would one have the same results for both?
I do hope my questions are clear now