Reputation: 2963
Below is the code where I'm learning the concepts of copy constructor and assignment operator. I'm referring the Bjarne Stroustrup C++11 book. But my program is crashing during when Vector class objects go out of scope. Here is the code I've written.
#include <iostream>
class Vector {
double* elements;
size_t size;
public:
Vector();
Vector(const Vector& vec);
Vector& operator=(const Vector& vec);
~Vector();
void print() {
for(size_t i = 0; i < size; ++i)
std::cout << elements[i] << ", ";
std::cout << "\b\b \b" << std::endl;
}
};
Vector::Vector() {
size = 10;
elements = new double[size];
for(size_t i = 0; i < size; ++i)
elements[i] = i + 1;
}
Vector::~Vector() {
if(elements != nullptr)
delete[] elements;
}
Vector::Vector(const Vector& vec) : elements { new double[size] }, size { vec.size } {
for(size_t i = 0; i < size; ++i)
elements[i] = vec.elements[i];
}
Vector& Vector::operator=(const Vector& vec) {
size = vec.size;
if(elements != nullptr)
delete[] elements;
elements = new double[size];
for(size_t i = 0; i < size; ++i)
elements[i] = vec.elements[i];
}
int32_t main(int32_t argc, char* argv[]) {
Vector vec1;
std::cout << "vec1 elements are: " << std::endl;
vec1.print();
Vector vec2 = vec1;
std::cout << "vec2 elements are: " << std::endl;
vec2.print();
return EXIT_SUCCESS;
}
Upvotes: 0
Views: 83
Reputation: 60208
There are 2 issues in your code. First, in the constructor, you are using the current size
member to allocate memory. Since it's uninitialized, this invokes undefined behavior. You should use the vec.size
to allocate memory:
Vector::Vector(const Vector& vec) : elements { new double[vec.size] }, size { vec.size } {
// ^^^
// ...
}
Second, you are not returning from operator=
which also invokes undefined behavior.
Vector& Vector::operator=(const Vector& vec) {
// ...
return *this; // you need to return
}
If you simply turn on all possible warnings, the compiler will tell you about these issues.
Upvotes: 3