Suppose I have the following class:
class foo{
public:
int someNum;
void calculation(int someNum);
};
Definition:
void foo::calculation(int someNum){
someNum = someNum;
}
Now in the line someNum = someNum
, which someNum is being referred to ?
If I do:
this->someNum = someNum
Then what is the second someNum ?
What is good naming style to avoid this problem ? For example, in objective-c, one prefixes "_" before a member variable name. (e.g.: _someNum);
Definition and Usage The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".
Some programmers find that always using an explicit this aids readability, while other find that it clutters code without adding value. Many company coding guidelines will specify whether this should be used or not, so you should endeavour to stick to the guideline in this case.
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .
'this' means 'current object'. In static methods there is no current object. In your example, try replacing this with new Main() .
Inside a member function the parameter name hides identical class member names, so in
void foo::calculation(int someNum){
someNum = someNum;
}
both someNum
s are referring to the parameter. It's a self-assignment that doesn't change this->someNum
.
In this->someNum = someNum;
, the second someNum
refers to the function parameter. So this assigns the value of the function parameter someNum
to the class member someNum
.
Common naming conventions include a m
or m_
prefix or a postfix _
to class members. A prefix underscore can be problematic because C++ reserves names beginning with an underscore followed by a capital letter.
Note that member initializer lists in constructors is a special case:
foo(int someNum) : someNum(someNum) { someNum = someNum; }
^ ^ ^ ^
| | | |
| ----------------------
| These three all refer to the parameter 'someNum',
| and not the class member.
|
The language requires this name to be referring
to a class member (or a base class) and so the
parameter called 'someNum' is not considered.
The variable declared in the innermost scope shadows the variables in the outer scopes. So, someNum = someNum'
in foo::calculation
has no effect on the member variable someNum
. Instead, someNum refers to the argument passed in. To help alleviate this, naming standards suggest prefixing your member variables with a consistent identifier - "m_", for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With