Solved

# operators vs functions; return types

Posted on 2004-10-09

I have a class called Vector - an array of doubles which performs lots of math operations (Matlab-style).

Let's take for instance a multiplication operation. It can be done in two ways:

1. As an operator, returning the result as a new object:

Vector Vector::operator *(Vector &v) // multiplies vectors if Lengths match

{

if (VLength!=v.VLength)

{

Vector retvec;

retvec.matherror = true;

return retvec;

}

Vector retvec(VLength);

if (retvec.memerror)

return retvec;

for (int l=0;l<VLength;l++)

retvec.data[l] = data[l]*v.data[l];

return retvec;

}

///////////////////////////

2. As a function, which accepts the "destination" object and changes it accordingly:

void Vector::MultVec(Vector &v, Vector &dest) // multiplies vectors if Lengths match

{

if (VLength!=v.VLength)

{

dest.matherror = true;

return;

}

dest.Resize(VLength);

if (dest.memerror)

return;

for (int l=0;l<VLength;l++)

dest.data[l] = data[l]*v.data[l];

}

///////////////////////////////////////////////

Now, when I call the first and the second versions, I write:

Vector v1, v2;

Vector v3, v4;

// ...

// Above, something is done with v1 and v2

v3 = v1 * v2;

v1.MultVec(v2, v4);

In the first case, "retvec" is created inside the operator and then copied into v3 upon returning.

In the second case, v4 is resized and filled with data.

While the first case is much more readable, obviously, the second case is more efficient when long vectors are concerned (no copying!).

Now, for my question: is there a way to avoid copying and still use the operators?

What I do _not_ want to do is allocate a dynamic object inside the operator and then return a pointer. This I won't accept as an answer! Any other suggestions? Is it maybe possible to do something like "assign output argument value"?

Thanks!