Introduction to Programming and C++

Contents Previous Topic Next Topic

Class member variables are variables which are duplicated for each instance of the class (that is, for each object). In general, to satisfy the requirements of invariance, all class member variables should be private. This is because, in almost all instances, the values a class member variable can take on should, conceptually, be restricted from the full range of possible variables.

For example, any measurement of an absolute physical quantity must be positive, and therefore a member variable storing such a value cannot be negative. If such a variable was public, it is possible that some function accessing the member variable may change it to a negative value. Because it is private, the only manner in which the variable may be accessed is through member functions of the same class, and it is a lot easier to ensure that the member functions are treating the member variables correctly.

Another benefit is that the member variables may change due to various reasons (e.g., optimizations). Consequently, if they were public, every single function which accessed that value would have to potentially be changed. By restricting access to member variables through member functions, only the member functions must be modified if there is a change to the variables.

The amount of memory required by each object of each class depends directly on the number of class member variables: a class consisting of two double member variables and three int member variables would require 2 × 8 bytes + 3 × 4 bytes = 36 bytes.


Contents Previous Topic Top Next Topic