Copy Constructor auto used in a spot where it shouldn't

My copy constructor works in a a spot which it shouldn't...
The reason it shouldn't be used there is because in that spot the copy constructor does something (created a pointer pointing to a random spot) that makes the program crash...
The constructor is used when i add (in class Vector) between two Vector array's and then put the answer (the Vector array) into a new Vector...
The copy constructor is actually used when the operator + sends back a Vector (it returns a new Vector by creating a new one and using the copy constructor to copy onto it what i wanted to return...).
This is my copy constructor and operator =:
Vector :: Vector (const Vector & Vect)
{
int i;
for (i = 0; i < VectorSize; i++)
VectorPtr [ i ] = Vect.VectorPtr [ i ];
}
Vector Vector :: operator= (Vector Num)
{
if (Num.VectorSize != VectorSize)
exit ( 1 );
int i;
for (i = 0; i < VectorSize; i++)
Num.VectorPtr [ i ] = VectorPtr [ i ];
return Num;
}
In the main() i do the following:
int i, Size, Size1;
cout<<"Enter the Size for Num:\n";
cin>>Size;
cout<<"Enter the Size for Num1:\n";
cin>>Size1;
Vector Num ( Size ), Num2 ( Size1 ), Num3 ( Size + Size1 );
for (i = 0; i < Size; i++)
{
cout<<"Enter the value to input into Vector 1 [ "<<i<<" ]: \n";
cin>>Num [ i ];
}
for (i = 0; i < Size1; i++)
{
cout<<"Enter the value to input into Vector 2 [ "<<i<<" ]: \n";
cin>>Num2 [ i ];
}
cout<<"Num + Num2:\n";
Num3 = (Num + Num2);
for (i = 0; i < Size; i++)
cout<<Num3 [ i ]<<' ';
cout<<endl;
}
Ive been asking more experienced programmers and they didn't know either...
Could some1 please help me out!?!?!?!
1
2
3
4
5
6
Vector :: Vector (const Vector & Vect)
{
int i;
for (i = 0; i < VectorSize; i++)
VectorPtr [ i ] = Vect.VectorPtr [ i ];
}


Is VectorPtr dynamically allocated? If yes, then that's your problem. You're not allocating memory for it here. You're just copying Vect.VectorPtr to some random area in memory -- corrupting the heap in the process.

Also, VectorSize is not initialized, either. So how many times is this loop supposed to run?
1
2
3
4
5
6
7
8
9
Vector Vector :: operator= (Vector Num)
{
if (Num.VectorSize != VectorSize)
exit ( 1 );
int i;
for (i = 0; i < VectorSize; i++)
Num.VectorPtr [ i ] = VectorPtr [ i ];
return Num;
}


Am I wrong that the for loop shouldnt change Num but this?
Topic archived. No new replies allowed.