Function or Variable

Hello people.

I started learning C++ today. I am familiar with C so I directly began by studying Classes.


In the classes tutorial is there a certain reason that the rect object has a function for area but not a variable?

Could it be



1
2
3
4
5
6
7
8
9
10
11
12
13
14

struct Rectangle {
 	
 	int width, height;
 	
 	public:
 	

 	void setvalues(int,int);
 	int area = width*height;
 	
 	
 };



Instead? Or is it better to have a function for area?


Thank you for your help. Have a great day.
Tradeoff. Design decision.

The area is a product of the other member variables.
If you always recompute it (in function call), you know that it matches the data.

If you do have it as separate member variables, then
1) Your objects use more memory (in your example at least 50% more)
2) All methods that update the other member variables, have to ensure that the area is updated
3) You don't have to recompute the area when it is queried

If the computation would be complex, and area would be queried way more often than the object changes, then it could make sense to cache the value in a member.
Topic archived. No new replies allowed.