• Create Account

### #ActualRavyne

Posted 09 May 2012 - 02:49 PM

I'd do it something like this (syntax may not be exact since I don't have a compiler in front of me):

namespace math {
class vector {
...
public:
vector& normalized() {
float inverse_length = 1 / this.length();

this.x *= inverse_length;
this.y *= inverse_length;
this.z *= inverse_length;

return *this;
}
...
};

vector& normalized_copy(vector to_normalize) {  // notice I take this by value
}
}


Here, the non-member, non-friend function takes the vector by value and then uses the member function normalize() to do the work. This pattern of passing in by value, modifying that object, and returning it modified and by reference enables the Return Value Optimization (RVO), so it not only re-uses the member implementation, but is efficient as well. RVO basically eliminates redundant copies of the object. Using a similar pattern, you can implement binary +, -, *, / and other operators as non-member, non-friend functions by re-using the unary member operators for +=, -=, *=, /=, etc.

### #2Ravyne

Posted 09 May 2012 - 02:48 PM

I'd do it something like this (syntax may not be exact since I don't have a compiler in front of me):

namespace math {
class vector {
...
public:
vector&amp; normalized() {
float inverse_length = 1 / this.length();

this.x *= inverse_length;
this.y *= inverse_length;
this.z *= inverse_length;

return *this;
}
...
};

vector&amp; normalized_copy(vector to_normalize) {  // notice I take this by value
}
}


Here, the non-member, non-friend function takes the vector by value and then uses the member function normalize() to do the work. This pattern of passing in by value, modifying that object, and returning it modified and by reference enables the Return Value Optimization (RVO), so it not only re-uses the member implementation, but is efficient as well. RVO basically eliminates redundant copies of the object. Using a similar pattern, you can implement binary +, -, *, / and other operators as non-member, non-friend functions by re-using the unary member operators for +=, -=, *=, /=, etc.

### #1Ravyne

Posted 09 May 2012 - 02:47 PM

I'd do it something like this (syntax may not be exact since I don't have a compiler in front of me):

namespace math {
class vector {
...
public:
vector& normalized() {
float inverse_length = 1 / this.length();

this.x *= inverse_length;
this.y *= inverse_length;
this.z *= inverse_length;

return *this;
}
...
};

vector& normalized_copy(vector to_normalize) { // notice I take this by value