Rahul Iyer
Rahul Iyer

Reputation: 21005

What happens if you don't use "this" within a class?

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);

Upvotes: 5

Views: 203

Answers (2)

T.C.
T.C.

Reputation: 137310

Inside a member function the parameter name hides identical class member names, so in

void foo::calculation(int someNum){
      someNum = someNum;
}

both someNums 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.

Upvotes: 9

Pradhan
Pradhan

Reputation: 16737

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.

Upvotes: 1

Related Questions