C++ Pointers
When function variable and class variable names collide


The standard practice / recommendation on how to handle a name collision between a class variable and a function variable is to append an underscore '_' to the end of one of the variable names.

Adding the underscore to the function variable name, makes the function signature look odd. And it is troublesome to change the class variable name when you are adding a mutator member function to an existing class and the variable is widely used throughout the class. Also the resulting code is untidy with some variable names having underscores and the remainder being without.

This C++ pointer shows you how to have member function variables and class variables with same name.

How to have a class variable name the same as the member function variable name.

The class variable name can be the same as the member function variable name by using the this pointer (this->) to reference the class wide variable that is being hidden by the local variable in the function's parameter list

The example is based on a simple class for a square. The class variables for the area and length of a side are area and length respectively. And we can use these names in the member function parameters, by using this technique.

#include <cmath> double area; double length; void Square::setArea(double area) { this->area = area; length = sqrt(area); } void Square::setLength(double length) { this->length = length; area = length * length; }