I’m a little confused about when things are copied and when they are referenced in C++. For example I have this very simple method where the arguments are references:
void setTimeSig(const int &tsNumerator, const int &tsDenominator) {
this->timeSigNum = tsNumerator;
this->timeSigDenom = tsDenominator;
}
Does this mean that because I’m using references when the function where setTimeSig is finished, the object with the timeSigNum and timeSigDenom will have these two fields empty? Or is it being copied at this point: this->timeSigNum = tsNumerator;
And one more question about the same thing:
class A{
public:
B bObject;
}
B b;
A a;
a.bObject = b;
Is bObject now referencing to b or does it contain a copy?
Any information on where or what I should read about this is much appreciated. I’m still confusing many things.
In the first example you are copying the values referenced by your function argument into your member variables.
Same thing in your second example, here you copy the values from your object b to your object a.bObject.
You are always using the assignment operator when using the operator= and the default way you do this is a so called shallow copy. When you have dynamic data in your class you need to be careful because the default one will not do since you will only copy the address of the dynamic data, and this data can be destroyed in either the original instance or the copied instance. In this case you need to do deep copying which means that you need to copy the dynamic data manually by overloading the assignment operator.
More about shallow vs deep copying here:
http://www.learncpp.com/cpp-tutorial/912-shallow-vs-deep-copying/
More reading from the same source on the subject of copy/assignment oprators:
http://www.learncpp.com/cpp-tutorial/911-the-copy-constructor-and-overloading-the-assignment-operator/