Like a struct, a class defines a new type of data defined in terms of other pieces of data. Something like βA Point is a thing that stores two double valuesβ:
class Point {
//member variables
double m_x;
double m_y;
};
The class declares the state of a given Point is defined by two pieces of data: the m_x and m_y. The variables declared in the class are member variables. (The variables that are βmembersβ, or a part, of the class.)
We have named the member variables with the prefix m_ (e.g. m_x instead of
x). This is a convention used to indicate that these variables are member variables (βm_β for βmemberβ) of a class. As we will see later, we will often also have functions that use a mix of member variables and local variables. The m_ prefix helps us to distinguish between the member variables that are a permanent part of the object and temporary local variables.
The m_ prefix is a weaker convention. Some codebases use it, while many will not. We will generally use it as we are learning about Object Oriented Programming to help clarify when we are referring to member variables.
Think of this class definition as a βblueprintβ that describes what a type of data is. The class
Point does not actually create a point anymore than the blueprint of a house gives you something to live in. To work with the Point data type, we must make a Point object from the blueprint.
Another term for creating an instance of a class is instantiating the class. When we say Point p1; we are instantiating the Point class to create an instance of a Point object named p1.
As usual, the name of the variable (p1) appears outside the box, and its data appears inside the box. In this case, the data is two separate member variables, which are represented with two boxes. We donβt know what values the member variables hold as we have not initialized them.
So far, this feels just like using a struct, only with more emphasis on terminology. However, unlike with a struct, we canβt access those values by saying p1.m_x or p1.m_y. Try compiling this code and notice what happens.