I have an overloaded operator + that returns an object of type IntArr, the sum of arrays is done well inside the function but when I do A = B + C the first two elements are not copied, leaving any numbers, why Does this happen?
Thanks
Overloaded function:
IntArr IntArr::operator+(IntArr A){
IntArr aux=*this;
if(aux.used+A.used>aux.size){
aux.espaciar(A.used); //espaciar aumenta el tamaño del array
}
for (int i=0;i<A.used;i++){
aux.p[aux.used+i]=A.p[i];
}
aux.used+=A.used;
return aux;
}
Copy Builder:
IntArr::IntArr(const IntArr &arr){
size=arr.size;
used=arr.used;
p=new int[size];
for(int i=0;i<used;i++){
p[i]=arr.p[i];
}
}
Main:
cout<<"\n> Array B\n"<<B; --> B=[99,1,2,3,4,5,6]
cout<<"\n> Array C\n"<<C; --> C=[1,2,3,4,5,6]
A=B+C;
cout<<"\n> Array A=B+C\n"<<A; -->da [5298323,6404288,2,3,4,5,6,1,2,3,4,5,6]
Space Function:
void IntArr::espaciar(int cant){
if (cant>5){
size+=cant;
}
else{
size+=5+cant;
}
int *aux=new int[size];
for (int i=0;i<used;i++){
aux[i]=p[i];
}
delete []p;
p=aux;
}
I solved it by overloading the operator =
, causing it to make the copy of the other object. In case someone helps you