I’m a little confused on the “knight being a copy thing”.
In C#, certain types (like structs) are passed by value and get copied, while other types (like classes) are passed by reference.
Does nothing pass by reference in C++?
I’m a little confused on the “knight being a copy thing”.
In C#, certain types (like structs) are passed by value and get copied, while other types (like classes) are passed by reference.
Does nothing pass by reference in C++?
It’s all by value, because the pointers (and use of address-of operators) provide the capability and core benefit (albeit not exactly the implementation) of pass by reference. The definition of each function gets to make that choice between receiving a copy of the address or a copy of the thing.
With a small possible exception of passing arrays, which look like objects that would be passed by value and duplicated, but are generally passed as a pointer behind the scenes. Even without passing by reference, you will be updating its member values directly (which are not pointers themselves).
e.g.
#include <iostream>
constexpr int ARRAY_SIZE = 5;
void multiplyValues(int[],int,int);
int main() {
int integers[ARRAY_SIZE]{1, 2, 3, 4, 5};
for(int i = 0; i < ARRAY_SIZE; i++)
std::cout << i << ": " << integers[i] << std::endl;
multiplyValues(integers, 3, ARRAY_SIZE);
for(int i = 0; i < ARRAY_SIZE; i++)
std::cout << i << ": " << integers[i] << std::endl;
return 0;
}
void multiplyValues(int integers[], int multiplier, int size) {
for(int i = 0; i < size; i++)
integers[i] *= multiplier;
}
Pedantically, the array pointer is still passed by value, but we just shouldn’t be caught out by the fact it is doing this thinking our array members are safe from mutation when they aren’t.
C++ uses value semantics by default though that doesn’t mean you can’t write a class that has reference semantics but they aren’t the norm.
What you have shown isn’t passing an array by value. Arrays decay into pointers.
void foo(int[]);
is exactly the same as writing
void foo(int*);
Yes, that’s exactly what I mean. It’s syntactic sugar for a pointer to the array, but that’s NOT what the code looks like to human eyes. So even though the function definition is still passing by value, it isn’t how it appears UNLESS you know about this nuance with arrays.
This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.