Insight 16.5.1.
Inside member functions, we always have access to the member variables of the object, even if they are private.
private, they are part of its implementation and outside code cannot access them directly. So how can outside code get or set the values of those member variables?
public so that outside code can call them.
class Point {
// Interface
// public member functions
public:
double getX() {
return m_x;
}
// Implementation
// private member variables
private:
double m_x;
double m_y;
}
getX is in a public block. Then look closely at the code inside the function getX(). What looks odd?
m_x in this function! It is not declared as a parameter, nor is it declared as a local variable. It is the member variable of Point named m_x. getX is a part of a Point object, and every object has a m_x, so it is assumed that m_x refers to the member variable of βthe current objectβ.
p1.getX();
p2.getX();
getX() function, there is only the getX() function that is a member of the Point class. (Point::getX() is the full name of this function - βthe getX that is a part of Pointβ.)
m_x to return.
getX function. When it does so, you will see a stack frame for Point::getX() and in that stack frame, you will see a variable called this that points at the object that is running the code. During the first call to Point::getX(), it will point to p1 since we called p1.getX() on line 23. Then, on line 26 when we call p2.getX(), this will be pointing at p2.
this is in SectionΒ 18.9. For now, you can think of it as an alias for βthe object running the codeβ. When we say m_x in a member function, it is understood to mean this->m_x or βthe m_x variable of the object running this codeβ.
m_x of the Point. But it can politely ask the Point to give it the value by calling a public member function getX(). The getX() function, as a member of the class, has access to the private information. Thus, we are providing an interface (public functions) so outside code can interact with the implementation (private variables) in a controlled way.
m_x variable. From main, we can call getX() but there is no public member function that allows us to change it.
m_red on line 6.
class Color {
private:
int m_red, m_green, m_blue;
public:
int getRed() {
return m_red;
}
};
int main() {
Color c1;
Color c2;
c1.getRed();
}
m_red value of whatever Color object getRed() was called onm_red value of c1.c1, it is possible that we could later call it on c2. So m_red is not guaranteed to be the value of c1.m_red value of c2.c2.m_red value of the Color class.m_red value. The class is just a blueprint for creating objects. The m_red variable is a member of each instance of the class.