Section 16.3 Classes
Like a
struct
, a class defines a new type of object. That datatype consists of other pieces of data that we refer to as its member variables or as instance variables. However, a class will also have member functions - functions that are a part of the class.
class Point {
...member functions...
...member variables...
};
Think of the 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. We call the object an instance of the class. For example, we might create a Point
object named p1
like this:
class Point {
...member functions...
...member variables...
double m_x, m_y;
};
int main() {
Point p1;
}
Here, we assume that a point has two member variables
m_x
and m_y
. That means any time we make a Point
object, we are creating a package that has two named parts:
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. However, unlike with a struct, we canβt access those values by saying p1.m_x
or p1.m_y
. That is because the members of a class are inaccessible outside of the class by default. Why are the inaccessible? How do we use them if they are inaccessible? We will tackle that next...
You have attempted of activities on this page.