Overload operator= issue

1
2
3
4
5
6
BitArray& BitArray::operator= (const BitArray& a) 
{
		for(int i = 0; i < a.arraySize; i++)
		barray[i] = a.barray[i];
		return *this;
}

I'm assigning it in main as:
 
BitArray ba2 = ba1;//Where ba1 is an existing, working object 


Everything else seems to work fine, however, this is continuously crashing anytime I try to assign anything. Any advice?
Are you dynamically allocating memory for your barray array?

If so, you will need to make sure that ba2's array is large enough to hold all the data in ba1's array before you start copying the data over.

If it's not, you will need to reallocate the array so that it's big enough.
Hmmm... That might be it. I tried it like this, but it still crashes.

1
2
3
4
5
6
7
BitArray& BitArray::operator= (const BitArray& a) 
{
           barray = new unsigned char[a.arraySize];
		for(int i = 0; i < a.arraySize; i++)
		barray[i] = a.barray[i];
		return *this;
}
BitArray ba2 = ba1; calls the copy constructor, not the assignment operator.
To clarify:
1
2
MyClass inst2 = inst1; //copy ctor
        inst2 = inst1; //operator= 
Last edited on
ne555: You are correct.

Here is the fixed code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
BitArray::BitArray(const BitArray& a)
{
	arraySize = a.arraySize;
	barray = new unsigned char[a.arraySize];
	for(int i = 0; i < a.arraySize; i++)
		barray[i] = a.barray[i];
}
BitArray& BitArray::operator= (const BitArray& a) 
{
	//check for self assignment
	if(this == &a){ return *this;}

	delete [] barray;
	arraySize = a.arraySize;
	barray = new unsigned char[a.arraySize];

	for(int i = 0; i < a.arraySize; i++)
		barray[i] = a.barray[i];

	return *this;
}

Topic archived. No new replies allowed.