I'm trying to implement BigInt for C++ and have run into a problem with copy constructors. You can see I commented out my original code for the copy constructor which was just *this = orig;
. But I have found that you need to use pointer instead to do this. I'm not entirely sure how this entirely works however and currently the code doesn't properly make a copy constructor.
-BigIntVector is a custom vector class. Compare to STL Vector.
BigInt.h:
class BigInt {
private:
BigIntVector bigIntVector;
bool isPositive;
int base;
unsigned int skip;
BigIntVector* ptr; //pointer to copy?
public:
// copy constructor
BigInt(BigInt const& orig);
// constructor where data value is passed as a long
BigInt(long num);
// destructor
~BigInt();
// binary '+' operator
BigInt operator+(BigInt const& other) const;
// unary '+' operator
BigInt operator+() const;
//more operator unloading functions
Here is my current implementation of the constructors in BigInt.cpp:
// copy constructor
BigInt::BigInt(BigInt const& orig) {
ptr = new BigIntVector;
*ptr = *orig.ptr;
//*this = orig;
}
// constructor where operand is a long
BigInt::BigInt(long num) {
//this->data = num;
ptr = new BigIntVector;
base = 10;
int sizeOfLong = 0; //holds size of num
int tempNum = num;
//get size of num
if (tempNum == 0) {
sizeOfLong = 1;
}
while (tempNum != 0)
{
tempNum /= 10;
++sizeOfLong;
}
//resize vector to match size of long
bigIntVector = BigIntVector(sizeOfLong);
if (num < 0) {
isPositive = false;
num *= -1;
}
else {
isPositive = true;
}
long pushedNum;
//cout << "num: " << num << endl;
for (int i = sizeOfLong - 1; i >= 0; --i) {
pushedNum = (long)(num%base);
bigIntVector.setElementAt(i, pushedNum);
num /= base;
}
}
// destructor
BigInt::~BigInt() {
//delete *this;
}
//code for overloading operators for BigInt below
Code for BigIntVector constructors:
BigIntVector::BigIntVector(long initialSize)
{
vectorTotalSize = initialSize;
vectorIncrementSize = initialSize;
vectorArray = (long *)malloc(initialSize*sizeof(long));
for (long i = 0; i < initialSize; i++) vectorArray[i] = 0;
nextValue = 0;
}