Friday, July 31, 2009

Accessing private class variables C++?

When you have private class variables in C++:





When accessing these variables from within a class method, why is it this-%26gt;variable, not this.variable like in Java. Also when accessing a pointer is it still this-%26gt;pointer?

Accessing private class variables C++?
Because "this" is defined as a pointer, and to access members of a pointer, you use "-%26gt;". Also, you do not have to use the "this" pointer to access member variables from a member function in a class. There are some instances like in someFunc() below where you may need to specify which variable to use with the same name, or if you want to make it perfectly clear that you are accessing a member variable.





class A


{


public:


A(int zzz)


{


z = zzz;


}





void someFunc(int z)


{


this-%26gt;z = z;


}





void someFunc2(int zz)


{


z = zz;


}





private:


int z;


}


No comments:

Post a Comment