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


suppose have following class:

class foo{ public:        int somenum;        void calculation(int somenum);  }; 

definition:

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

now in line somenum = somenum , somenum being referred ? if do:

this->somenum = somenum 

then second somenum ?

what naming style avoid problem ? example, in objective-c, 1 prefixes "_" before member variable name. (e.g.: _somenum);

inside member function parameter name hides identical class member names, in

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

both somenums referring parameter. it's self-assignment doesn't change this->somenum.

in this->somenum = somenum;, second somenum refers function parameter. assigns value of function parameter somenum class member somenum.

common naming conventions include m or m_ prefix or postfix _ class members. prefix underscore can problematic because c++ reserves names beginning underscore followed capital letter.


note member initializer lists in constructors special case:

foo(int somenum) : somenum(somenum) { somenum = somenum; }                    ^        ^          ^         ^                    |        |          |         |                    |        ----------------------                    |        these 3 refer parameter 'somenum',                    |        , not class member.                    |      language requires name referring      class member (or base class) ,        parameter called 'somenum' not considered. 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -