operator= Overloading error

I'm attempting to overload the = operator for a class designed to manage arrays of integers (inb4 vectors). But anytime there is an '=' operation in the main file I get the following error:
1
2
main.cpp:29: error: assignment of function ‘IntArray A()’
main.cpp:29: error: cannot convert ‘IntArray’ to ‘IntArray()’ in assignment


Here's the actual code from the overload:
1
2
3
4
5
6
7
8
IntArray& IntArray::operator= (const IntArray &arrayB) {
		delete[] array;
                size = arrayB.size;
		for(int i=0;i<size;i++) {
			array[i]=arrayB.array[i];
		}
		return *this;
	} 


and specific line from main.cpp in question is just A=B; where A and B are declared instances of IntArray.

Thanks in advance for any help.
where A and B are declared instances of IntArray.


You're probably wrong about this. You're probably declaring either A or B as a function prototype and not as an instance.

1
2
IntArray A();  // a FUNCTION PROTOTYPE, not an object
IntArray B;  // an object. 




Also...

1
2
3
4
5
		delete[] array;  // <- array is delete[]'d here
                size = arrayB.size;
		for(int i=0;i<size;i++) {
			array[i]=arrayB.array[i];  // <- you're writing to a delete[]'d pointer here.
  // MEMORY CORRUPTION!  bad bad bad 


Lastly... you need to guard against self-assignment. If you do A = A; your assignment operator will not work properly.
They're declared in the main file like this:
1
2
    IntArray A();
    IntArray B(5);

So maybe it has to do with my constructor?

Edit: I changed the code to:
1
2
    IntArray A(4);
    IntArray B(5);


to see what it could do and the errors were gone which is confusing to me because I think the constructors are functionally identical.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
	IntArray::IntArray() {
		size = 10;
		array = new int[size];
		for(int i=0;i<size;i++) {
			array[i]=0;
		}
	}
	IntArray::IntArray(int newSize) {
		if(newSize > 0)
			size = newSize;
		else {
			cout << "Input size is invalid." << endl;
			exit(1);
		}
		array = new int[size];
		for(int i=0;i<size;i++) {
			array[i]=0;
		}
	}
Last edited on
There is nothing wrong with your constructors.

They're declared in the main file like this:
IntArray A();
IntArray B(5);


Yes... that's exactly what I said.

IntArray A(); does not create an object named 'A'. Instead, it's a function prototype, declaring a function named 'A' that takes no parameters and returns an IntArray.

1
2
3
4
5
6
IntArray A()
{
 // a function ... not an object
}

IntArray A(); // a function prototype, not an object 



IntArray B(5); is different because the value of '5' makes it clear that this is passing an argument to the ctor and not defining a function parameter. Therefore 'B' is actually an object as you intended.
Right, thanks for your help. The instructor for the class wrote the main file so I assumed everything in it was correct. Oh well. I got everything figured out.

Thanks again.
Topic archived. No new replies allowed.