can anyone help me with copy constructors. i am writing a program with a class that stores an array of integers and im not sure how to write the copy constructor so that it copies the array into the new class.
can anyone help me with copy constructors. i am writing a program with a class that stores an array of integers and im not sure how to write the copy constructor so that it copies the array into the new class.
1) It takes a const reference parameter of type className.
2) It has no return value
3) It's called when you pass an object by value to a function, or return an object by value from a function, or create an object with another object.
Inside the copy constructor, you would copy the elements from the other objects array:
Code:for(int i = 0; i<12; i++) { memberarray[i] = otherObject.memberarray[i]; }
i tried implementing the code you suggested but i get an error message saying that my original object.array is undeclarred
could that be because i didnt put new array[0] in the constructor?
Last edited by nessie; 04-24-2005 at 07:19 AM.
i got that code to work using
but it is now generating random numbers to the new arrayCode:int i=0; while(i<size){ b.array[i] = array[i]; cout<<b.array[i]<<endl; ++i; }
You've got this backwards:
b.array[i] = array[i];
array[i] is the new object's member(that is why it is not preceded by an object name).
b.array[i] is the old object's member. b is the object that is the function argument. You want to assign old to new. But, you are assigning new to old, and new is filled with junk values, so you are overwriting b's values with junk values. In fact, that shouldn't even compile if you followed step 1, which said the parameter should be a const reference type. When you put const in front of a parameter, it ensures that the function cannot change the object. Whenever a function shouldn't change the argument you send to the function, you should put const in front of the parameter name in the function definition. That way the compiler can alert you to any errors you are making--just like here.
Last edited by 7stud; 04-24-2005 at 08:21 AM.