0

I'm trying to use + to add 2 vector (mathematical vector). Here's my code:

class Vector{
    double v[Max_size];
    int dim;
public:
    int getDim() const;
    Vector();
    Vector(int n);
    Vector(const Vector& a);
    Vector add(const Vector&b);
    friend Vector operator+(Vector summand1, Vector summand2);
};

Operator overloading:

Vector operator+(Vector summand1, Vector summand2){
    int dim1 = summand1.getDim();
    int dim2 = summand2.getDim();
    assert(dim1 == dim2);
    Vector sum(dim1);
    int i;
    for(i = 0; i < dim1; i++){
        sum.v[i] = summand1.v[i] + summand2.v[i];
    }
    return sum;
}

And how I use it:

Vector m = v+t;

When I run the code, it always shows that m is (0,0) (2D vector), which is the default value generated by the constructor. What's wrong with it? Thanks!

Minh Nghĩa
  • 854
  • 1
  • 11
  • 28

1 Answers1

1

Your copy constructor:

Vector::Vector(const Vector& a){
    dim = a.dim;
    Vector(dim);
}

correctly sets the value of the dim member, but has not other side effect.

You should have a variant of the following code:

Vector::Vector(const Vector& a) : dim(a.dim) {
    std::copy(std::begin(a.v), std::end(a.v), v);
}

This will actually copy the data present in the parameter, and you will see the correct behavior for the code:

// Copy constructor called here, but did not correctly copy the data before.
Vector m = v + t;

For a better (by that I intend simpler and safer) Vector class, if you have access to a compiler that is at least C++11 compliant, you can write:

class Vector{
    std::array<double, Max_size> v; // Note the std::array here.
    int dim;
public:
    int getDim() const;
    Vector();
    Vector(int n);
    Vector(const Vector& a);
    Vector add(const Vector&b);
    friend Vector operator+(Vector summand1, Vector summand2);
};

The std::array will take care of everything, provided you write your copy constructor like this:

Vector::Vector(const Vector& a) : v(a.v), dim(a.dim) {

}

Or, even better, you could then let the compiler generate the copy constructor itself, with the same behavior.

rems4e
  • 3,112
  • 1
  • 17
  • 24
  • bingo! but what is the meaning of : dim(a.dim) ? – Minh Nghĩa Apr 25 '16 at 17:24
  • dim(a.dim) constructs the dim member with the value a.dim. In C++, it is preferred, more optimized and sometimes mandatory to initialize class members like that. Search "member initialization list" for more info on this syntax. – rems4e Apr 25 '16 at 18:35