OpenSource For You

‘This’ pointer and scopes

-

Those of us who have programmed in C++ are familiar with the ‘this’ pointer, which is a special type that points to the object of which a non-static member function is being invoked. Let ‘X’ be a class, and my_A an object of class X. We have a member function in X named foo.

Consider the code snippet above. In the member function set_birthyear, we used this->birthyear to refer to the data member birthyear of the object on which the function set_birthyear is invoked. Note that we typically do not write this->birthyear, but just write the assignment as birthyear = year; since the usage of ‘this’ is implicit. When you invoke my_a.set_birthyear (1971), it is as if you have written the invocation as my_a. set_birthyear(&my_a, 1971). THH firsw arjuphnw Ls WHH this pointer, which is the pointer to the receiver object on which the function is invoked. Note that we cannot explicitly declare the this pointer, nor can we assign a different object to the this pointer in C++. It is not possible for me to pass a my_b object address as the this pointer in the above call, to set_birthyear. However, ‘this’ behaves differentl­y in Javascript, and it would be useful to understand the difference. Before we discuss Whls, OHW us brlhfly HXSOORH sfoshs.

In C or C++, you can create a new scope by block statements. Whenever you open a new curly brace, it creates a new scope. For example, consider the following code: class X { int age; int birthyear; string my_name; public: void set_birthyear (int year) {

this->birthyear = year;

} } .... X my_A; // equivalent to my_A.set_birthyear(&my_A, 1971) my_A.set_birthyear(1971); int my_var = 1; int main(void) {

int my_var = 10; /* start a new scope here by a block */ { int my_var = 20; int your_var = 30; //This prints 20 and 30

Newspapers in English

Newspapers from India