Im writing a class to try out dynamic memory allocation. The class is for a dynamic array of integers and has 3 data members. A pointer to the first array element, an integer for array size and one for capacity. The << operator is also overloaded to allow printing of the array. When i declare my array then create a vector object and try to print it segmentation faults. I have other methods but only the ones being tested are posted here. The rest of them are never called (commented out). The vector array should be initialized to null in the constructor hence the 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
friend ostream& operator<<(ostream&, Vector);
int * vectorArray;
I have other methods but only the ones being tested are posted here. The rest of them are never called
Not everything gets called explicitly.
For example, you are passing rightOp by value to operator <<, so a local copy is created, and then it's destroyed. The copy constructor and destructor are invoked "silently".
Did write you own version of them? Perhaps you forgot to assign a value to vectrorSize in the copy constructor, leaving vectorSize uninitialized.
Your operator<< implementation takes its Vector parameter by value, which means it will take a copy of the argument fed to it. However, you don't explicitly supply a copy constructor and the defaulted one is not adequate.
If you were to change operator<< to take it's Vector parameter by reference, your problem would go away since there would be no copy construction involved. (This is assuming you've defined a destructor that frees the memory. If you haven't, the only issue would be a memory leak.)
Your copy constructor is incorrect. It doesn't initialize vectorArray, vectorSize or vectorCapacity to meaningful values, and it copies to the uninitialized value (read:random address) held by vectorArray.