Reputation: 93
Hi I have a class which includes an array, I'm not passing this through my class constuctor (could be going wrong here?) The array is just defined in the class then initialized in a read method.
But in the main I make an instance of the class like:
myClass myClass1;
Then do:
myClass1 = myClass2;
Now I use a bubble sort method on the first class instance like:
MyClass1.sort();
Now when I write both of these instances out to text after the sort they are both sorted?
I have had a read into shallow and deep copys, but I can't understand why a method called after the shallow copy, would result in both of them being sorted? Is this expected behavoir?
a little more information:
In my class I just define the array as:
static string myArray[5];
then in a write method I write the 5 elements to it, is there a better way of doing this, I have to use a method to intialize it though.
Upvotes: 2
Views: 153
Reputation: 36487
How is your array defined/created? If you create it with new
and reference it with a pointer, you'll need a custom copy constructor creating a deep copy (i.e. creating a new instance of the array and copying its contents). The default copy constructor will only do a shallow copy, so both instances would use the same memory (i.e. both pointers' point to the same array on the heap).
This will work with the default copy constructor:
class myclass {
char text[256];
}
This won't work with the default copy constructor (at least not as expected):
class myclass {
char *text;
myclass() : text(new char[256]) {}
~myclass() { delete [] text; }
}
A member defined as static
will never be copied. All instances share it without further code required:
class myclass {
static char text[256];
}
A copy constructor for the second case could look like this (note this is simplified and not checking for valid values and such):
myclass(const myclass &base) : text(new char[256]) { strcpy(text, base.text); }
General rule of thumb:
Do I use any pointer member that is assigned the return value of some new
? If so, write a copy constructor. If not, hen use he default one (unless you've got other reasons).
Upvotes: 3
Reputation: 234474
In my class I just define the array as:
static string myArray[5];
Should I declare it in the header, as its only declared in the cpp file? As its still copying both.
If you declare that outside of a class definition it will be a global variable. There will only be one instance of it. You need to declare it inside the class, and not static
:
class MyClass1 {
// other things...
string myArray[5];
};
In any case, this kind of basic question is better answered by consulting a good C++ introductory book.
Upvotes: 2