Reputation: 327
I am learning to write code in c++, and I'm having trouble with operators. I created this class:
typedef float data_type;
class eucVector
{
public:
unsigned int dim;
data_type *vdata;
eucVector();
eucVector(unsigned int);
eucVector(unsigned int, data_type*);
~eucVector();
void print();
eucVector operator + (eucVector);
};
This class is basically an euclidean vector, of variable size (dim), and the operator + would simply add every entry of the vectors involved.
This is the implementation of that operator:
eucVector eucVector::operator + (eucVector y)
{
eucVector c(dim);
for (unsigned int i=0; i<dim; i++)
{
c.vdata[i] = vdata[i] + y.vdata[i];
}
return c;
}
Now, the main function looks like this:
int main()
{
eucVector a(3), b(3), c;
for (int i=0; i<3; i++)
{
a.vdata[i] = 3*i-1;
b.vdata[i] = 2*i +3;
}
cout << "a = ";
a.print();
cout << "b = ";
b.print();
cout << endl;
c = a+b;
cout << "a = ";
a.print();
cout << "b = ";
b.print();
cout << endl << "c = ";
c.print();
return 0;
}
And the result is a vector c filled with zeroes, and more importantly, the vector b, which has no commands changing it, changes its 2 first entries after the "c=a+b;" line.
I have no idea what's going on, and I'm dealing with this since yesterday. It's a bit frustrating not being able to get such a simple function working... Help me please!
Thank you very much.
PS: I don't know if it matters, but I'm using Code::Blocks as my IDE, and I'm on a pc with windows 8.
This are the other functions:
eucVector::eucVector()
{
dim = 0;
vdata = NULL;
}
eucVector::eucVector(unsigned int newDim)
{
dim = newDim;
vdata = (data_type *)calloc(dim, sizeof(data_type));
}
eucVector::eucVector(unsigned int newDim, data_type* newdata)
{
dim = newDim;
vdata = (data_type *)calloc(dim, sizeof(data_type));
for(unsigned int i=0; i<dim; i++)
{
vdata[i] = newdata[i];
}
}
eucVector::~eucVector()
{
free(vdata);
}
void eucVector::print()
{
for (int i=0; i<dim-1; i++)
cout << vdata[i] << ", ";
cout << vdata[dim-1] << endl;
}
Upvotes: 0
Views: 101
Reputation: 72271
I suspect it's the Rule Of Three getting you.
Since you don't define a copy constructor, and frequently pass the objects by value into and out of functions, C++ will make copies of the objects in a simple way, where the copies share the same pointer member. But then if one of the copies is destroyed, it does call your destructor, and memory is freed, even if it's being used by another eucVector
.
Upvotes: 3