c++ copy constructor, after copy random value -
i have errors copy constructor cant figure out, main question @ moment brought out in test programs comments. why second print out big number, , not three? thank in advance help.
template<class t> class array { private: t *cont; unsigned int size; public: array()=default; t& elementat(unsigned int i) { return cont[i]; } array( const array &a ) { cont = new int[ size ]; ( int = 0; < size; i++ ) cont[ ] = a.cont[ ]; } array& operator = (const array& a) { int i,min_size; if(size < a.size) min_size = size; else min_size = a.size; for(i=0; i<min_size; i++) cont[i] = a.cont[i]; return (*this); } void addelement(t element) { t *new_cont = new t[size + 1], *old_cont = cont; (int = 0; < size; i++) { new_cont[i] = old_cont[i]; } new_cont[size] = element; size++; cont = new_cont; delete old_cont; } unsigned int getsize() const { return size; } ~array() { delete [] cont; } };
and part of test program:
array<int> numbers; numbers.addelement (5); numbers.addelement (11); numbers.addelement (3); cout << numbers.getsize()<<endl; // here output: 3 cout<< numbers.elementat(1)<<endl; // output: 11 myarray<int> copy2; copy2 = numbers; cout << copy2.getsize()<<endl; // why output: 2686697, in here? why isn' t 3. cout<< copy2.elementat(1)<<endl; // output: 11
you using wrong size
allocate memory in copy constructor.
array( const array &a ) { // size copy first. without it, size unitialized // value, lead undefined behavior. size = a.size; cont = new int[ size ]; ( int = 0; < size; i++ ) cont[ ] = a.cont[ ]; }
the other problem see implementation of default constructor. default constructor can used in 2 ways:
array<int> numbers;
or
array<int> numbers = array<int>();
the former result in uninitialized data while latter result in initialized data implementation. see details here.
you can change default constructor to:
array() : size(0), cont(null) {}
to make code work identically in either way of constructing object.
the third problem operator=
function. not perform true assignment. stores minimum number of elements 2 objects. try this:
array& operator = (const array& a) { // make statements 'a = a;' noop. if ( != &a ) { // if size of lhs larger or equal size // of rhs, lhs has enough memory store data // rhs. if ( this->size >= a.size ) { this->size = a.size; for(int i=0; i<a.size; i++) cont[i] = a.cont[i]; } else { // size of lhs smaller size of rhs, // not have enough memory store data // rhs. dellocate old memory. allocate new memory. // copy data. this->size = a.size; delete [] cont; cont = new int[this->size]; for(int i=0; i<a.size; i++) cont[i] = a.cont[i]; } } return (*this); }
Comments
Post a Comment