I just started shifting from Java to C++ and I am having a hard time with the C++'s subtle syntax. I was writing this code:
class Box{
public:
int length;
int width;
// a few more function over loaded constructors
Box( Box box_object_to_copy ){
this->length = box_object_to_copy.length;
this->width = box_object_to_copy.width;
}
};
I am running into compilation error. I am not sure, but my friend pointed out that the constructor taking the Box object is at fault as it is not taking the object as reference. But my point is reference or value, it should work at least. Passing by value basically creates another copy, that is the only immediately visible difference between the two...
PrasannaKumar Muralidharan
Kernel developer @ Witworks
The constructor used to copy the value from another object of the same class is called as copy constructor. It takes only a reference, not value. What you have passed is value.
Change the definition to:
Box (Box &obj) { this.width = obj.width; this.height = obj.height; }Your declaration implies that the object is passed by value. It is a copy of the object. To get a copy 'copy constructor' is called. So this will result in an infinite loop. So in C++ you can only pass by reference in case of copy constructor.
Java uses pass by reference always for non-primitive data type. So you don't have a problem.