Derived member variables.

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?
 
A

Alf P. Steinbach

* Jason Heyes:
Do you only add derived member variables to a class to improve performance?

Although also this question smells strongly of HOMEWORK, I can't see
what you'd "gain" by copying or paraphrasing a serious answer, so.

Assuming 'derived member variable' means 'a member variable whose value
can be derived from other member variables': no, it can be added for
reasons other than performance.

A variable has functionality that a computed value has not; you might
learn a bit by pondering the question of what that functionality is.
 
J

Jason Heyes

Alf P. Steinbach said:
* Jason Heyes:

Although also this question smells strongly of HOMEWORK, I can't see
what you'd "gain" by copying or paraphrasing a serious answer, so.

Assuming 'derived member variable' means 'a member variable whose value
can be derived from other member variables': no, it can be added for
reasons other than performance.

A variable has functionality that a computed value has not; you might
learn a bit by pondering the question of what that functionality is.

Are you referring to the constness of a variable as opposed to a computed
value? The computed value can be stored in another variable so the same
functionality is there isn't it? Please help me understand.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,184
Messages
2,570,976
Members
47,536
Latest member
MistyLough

Latest Threads

Top