I have always assumed that passing variables with [pass-by-value] in [c++], makes a copy of them, and so the function receiving these copies can not change the original variable's content.
I guess it is because when argument is passed by value, [copy-constructor] is called, and if it is not overridden by the programmer, the default [copy-constructor] does [shallow-copy] instead of [deep-copy]!
So my question is that why they called it pass-by-value, while in the case of having pointers in the class, the function has access to the reference of that pointer and can damage it. Also is this conclusion correct? "Whenever have pointers in the class, and you might pass an object of that class by value as a function argument, define the copy constructor!"
If this error is famous, does anyone know the name or phrase to this problem?
Below is my code that resulted in a modified list. Objects of this class contain an int member variable as well as a pointer to a list of nodes member variable.
class ComplicatedObject{
public:
ComplicatedObject();
~ComplicatedObject();
//ComplicatedObject(const ComplicatedObject& c); // copy construtor
//ComplicatedObject& operator=(const ComplicatedObject& c); // =operator
int int_member_varialbe_; // an int member variable
void addToList(int d);
void printList();
private:
struct node{
int data;
node* next;
};
node* head_; // points to the beginning of a list (linkedlist of int)
};
The below code prints 2. And then prints 2 3 !
Test.cpp:
void myfunction(ComplicatedObject obj){
obj.addToList(3);
obj.int_member_variable_ = 5;
}
int main(void){
ComplicatedObject c_object;
c_object.addToList(2);
c_object.printList(); //prints 2
cout << "int member variable befor passing:";
cout << c-object.int_member_variable_ << endl; //prints 6 (a default value)
myfunction(c_object); //pass-by-value
cout << "int member variable after passing:";
cout << c-object.int_member_variable_ << endl; // prints 6 (not 5)
c_object.printList(); // prints 2 3 ! List get changed!
return 0;
}