J
Jason Heyes
Do you only add derived member variables to a class to improve performance?
Here is an example:
int square(int integer) { return integer * integer; }
vector<int> compute_squares(vector<int> integers)
{
vector<int> squares;
transform(integers.begin(), integers.end(), back_inserter(squares),
square);
return squares;
}
class MyIntegers
{
vector<int> integers;
vector<int> squares;
public:
MyIntegers(vector<int> integers_) : integers(integers_),
squares(compute_squares(integers)) { }
void scale(int factor)
{
transform(integers.begin(), integers.end(), integers.begin(),
bind2nd(multiplies<int>(), factor)));
transform(squares.begin(), squares.end(), squares.begin(),
bind2nd(multiplies<int>(), factor * factor)));
}
vector<int> get_squares() const { return squares; }
};
Since MyIntegers has a derived member variable called squares, it's member
function get_squares only has to return a value. Therefore if get_squares is
called more than any other function, then the addition of squares to
MyIntegers pays off at run-time. Is this the only reason you would add
derived member variables to a class?
Here is an example:
int square(int integer) { return integer * integer; }
vector<int> compute_squares(vector<int> integers)
{
vector<int> squares;
transform(integers.begin(), integers.end(), back_inserter(squares),
square);
return squares;
}
class MyIntegers
{
vector<int> integers;
vector<int> squares;
public:
MyIntegers(vector<int> integers_) : integers(integers_),
squares(compute_squares(integers)) { }
void scale(int factor)
{
transform(integers.begin(), integers.end(), integers.begin(),
bind2nd(multiplies<int>(), factor)));
transform(squares.begin(), squares.end(), squares.begin(),
bind2nd(multiplies<int>(), factor * factor)));
}
vector<int> get_squares() const { return squares; }
};
Since MyIntegers has a derived member variable called squares, it's member
function get_squares only has to return a value. Therefore if get_squares is
called more than any other function, then the addition of squares to
MyIntegers pays off at run-time. Is this the only reason you would add
derived member variables to a class?