0% found this document useful (0 votes)
27 views18 pages

This Keyword Notes Final

Uploaded by

Putta Swamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views18 pages

This Keyword Notes Final

Uploaded by

Putta Swamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

In C++, the this pointer is a special pointer available inside non-static member functions of

a class. It points to the object for which the member function is called, allowing access to the
object's members and methods.
Key Points about the this Pointer
1. Implicit Argument: The this pointer provides a way to refer to the calling object.
It acts as an implicit argument to non-static member functions.
2. Type: The type of this is a constant pointer to the type of the class
(e.g., ClassName* const), meaning it points to the object that invoked the
member function and cannot be reassigned.
3. Use Cases:

 Disambiguation: It helps to disambiguate between member variables


and parameters or other local variables with the same name.
 Returning Object Reference: It enables method chaining by
returning *this from a member function.
 Accessing Members: Facilitates access to members of the class.
4. Not Available in Static Members: The this pointer is not accessible in static
member functions because they do not operate on a specific instance of the class.
Example Code
Here is an example that demonstrates the use of the this pointer:
cpp

Copy code
#include <iostream>

using namespace std;

class MyClass {

private:

int value;

public:

MyClass(int value) {

// Using 'this' to distinguish member variable from parameter

this->value = value;

// Member function returning the current object


MyClass& setValue(int value) {

this->value = value; // Using 'this' again for clarity

return *this; // Returning the current object

void display() {

cout << "Value: " << this->value << endl; // Also can use value directly

};

int main() {

MyClass obj(10);

obj.display(); // Output: Value: 10

obj.setValue(20).display(); // Chaining method calls

return 0;

}
Explanation of the Example
1. Class Definition: MyClass has a private member variable value.
2. Constructor:

cpp

Copy code
MyClass(int value) {

this->value = value;

 The constructor initializes the member variable value. The this pointer
distinguishes the parameter value from the member variable.
3. setValue Method:

cpp

Copy code
MyClass& setValue(int value) {

this->value = value;
return *this; // Returning the object to allow chaining

 This method changes the value of value and returns a reference to the
current object.
4. Display Method:

cpp

Copy code
void display() {

cout << "Value: " << this->value << endl;

}
5. Main Function:

 In main, an object of MyClass is created, and its value is displayed.


 The setValue method is called, using method chaining to change the
value and display it again.
Output
When you run the code, the output will be:
Value: 10

Value: 20

Conclusion
The this pointer is a powerful and essential feature in C++ that facilitates object-oriented
programming. It allows for member function clarity, method chaining, and helps to maintain
clean code. Understanding how to use the this pointer effectively can lead to better design
choices in C++ applications.

Introduction
 It is important when operators are overloaded.
 The 'this' pointer is automatically passed to a member function when it is
called.
 It is used to represent an object that invokes the member function.
 It is not available in static member functions as static member functions can
be called without any object.

The 'this' pointer is used in two situations:


1. When local variable's name is same as member's name.
2. When a reference to a local object is returned.
 Friend function do not get 'this' pointer, because friends are not members
of a class.
 Only member functions have a 'this' pointer.
Example : Demonstrating the working of 'this' pointer
1. When local variable's name is same as member's name.

#include<iostream>
using namespace std;
class TestThisPointer // Local variable is same as a member's name
{
private:
int a;
public:
void getvalue(int a)
{
this->a = a; // The 'this' pointer is used to retrieve the object's x hidden
by the local variable 'x'
}
void showvalue()
{
cout << "Value of A = " << a << endl;
}
};
int main()
{
TestThisPointer tp;
int a = 10;
tp.getvalue(a);
tp.showvalue();
return 0;
}

Output:
Value of A = 10

2. When a reference to a local object is returned.


#include<iostream>
using namespace std;
class TestThisPointer
{
private:
int a;
int b;
public:
TestThisPointer(int a = 0, int b = 0) //Parameterized Constructor
{
this->a = a;
this->b = b;
}
TestThisPointer &getvalue(int x)
{
a = x;
return *this;
}
TestThisPointer &getval(int y)
{
b = y;
return *this;
}
void showvalue()
{
cout<<"Value of x = "<<a<<endl;
cout<<"Value of y = "<<b<< endl;
}
};
int main()
{
TestThisPointer tp(5,5); //Chained function calls. All calls modify the same
object as the same object is returned by reference
tp.getvalue(10).getval(20);
tp.showvalue();
return 0;
}
Output:
Value of x = 10
Value of y = 20
In the above example, when a reference to a local object is returned, the returned
reference can be used to chain function calls on a single object.
Source Code
#include<iostream>
using namespace std;
class Rectangle
{
private :
int length;
int breadth;
public :
Rectangle(int length=0,int breadth=0)
{
this->length=length;
this->breadth=breadth ;
}
int area()
{
return length*breadth;
}
};
int main()
{
Rectangle r(10,5);
cout<<"Area : "<<r.area();
return 0;
}
Output
Area : 50
This Pointer Example in C++

This program defines a Rectangle class with private data members length and
breadth, and a public member function area() that calculates and returns the area
of the rectangle. In the constructor of the class, default values of length and
breadth are set to 0. The constructor takes arguments for length and breadth and
initializes the corresponding data members using this pointer.
In the main() function, an object r of the Rectangle class is created with length =
10 and breadth = 5. The area() function of the object r is called to calculate and
display the area of the rectangle.

This keyword
In C++ programming, this is a keyword or unique pointer variable (implicit
pointer or implicit object parameter) available within non-static member function
of a class that refers(points) to the current instance (object) of the class (Every
object in C++ has access to its own address through an important pointer
called this pointer). It holds the address of class objects, letting the object
access its own member variables and functions (makes it easy for member
function to access data members). In other words, this pointer is used to
distinguish data members of the class and member function when having the
same name.
The 'this' pointer is a constant pointer that holds the memory address of the
current object and internally created at the time of function call.
Example:
Suppose we create an object named objectA of class A. The
class A has a non-static member function foo(). When we call the function
using objectA as objectA.foo(), the pointer this is passed to the function by the
compiler implicitly. this pointer can be accessed from inside the function body to
access data members of objectA because it stores the address of objectA.
The "this" pointer is automatically passed as a hidden argument in non-static
member function calls.
So, when we call the function foo() we are calling foo(&objectA) because C++
adds a new parameter to the function. Since a new parameter is passed to the
function, C++ converts the function definition from
void A::foo ();
internally to
void A::foo (A* const this);
This new parameter is consistently named this and is a hidden pointer inside
every class method (functions) that points to the class object.
Note: Friend functions don't have access to this pointer because such functions
are not class members.
Friend functions do not have a this pointer, because friends are not members of a
class. Only member functions have a this pointer.
Syntax Of 'this' Pointer: When creating or using the 'this' pointer, the 'this'
keyword is used in conjunction with the arrow operator (->) along with the name
of the member or method being referred to.
void functionName()
{
this->memberName = value;
}
this.var_name;
or
this->var_name;

Here,
 functionName refers to the identifier/ name you have given to the function.
 The term this-> represents the 'this' pointer and memberName refers to the
respective member of the class you are trying to access.
Whenever we call a member function in association with an object, the object’s
address is implicitly passed as a hidden first argument received in the called
member function using a special pointer known as this pointer.
In terms of usage, there are these three main uses of this keyword in
the C++ programming language. They are,
 This keyword in C++ language is generally used to refer current class instance
variable.
 This keyword in C++ language is generally used to declare indexers.
 This keyword in C++ language is generally used to pass the current object as
the parameter to another method.
Use Case 1: Resolving Variable Shadowing (ambiguity between the instance
variable and parameter):
Let's understand the problem if we don't use this keyword by the example given
below:
class student
{
int id;
String name;
student(int id,String name)
{
id = id;
name = name;
}
void display()
{
System.out.println(id+" "+name);
}
}
Class MyPgm
{
public static void main(String args[])
{
student s1 = new student(111,"Anoop");
student s2 = new student(321,"Arayan");
s1.display();
s2.display();
}
}
Output: 0 null
0 null
In the above example, parameter (formal arguments) and instance
variables are same that is why we are using this keyword to distinguish
between local variable and instance variable.

Variable shadowing is a very common use case for the ‘this’ pointer.
Variable shadowing occurs when a class member variable and another
parameter variable or local variable have the same name. The local variable
‘shadows’ the class member variable. To reference the class member
variable, we use the ‘this’ keyword.
Syntax
int value;
public:
void demoFunction(int value)
{
this->value = value;
}
From the syntax, note that the variable that is being referenced using the
‘this’ keyword is the class member variable and the other one is the
parameter variable that is available only locally.
Example
#include <iostream>
using namespace std;
class Test
{
//this is a class member variable
string testString;
public:
//non-static member function
void setData(string testString)
{
//this is refering to the class member variable
this->testString = testString;
}
void getData()
{
cout << "The string is: " << this->testString << endl;
}
};
int main()
{
//create the object
Test test;
//call the member function
test.setData("This is a test for variable shadowing!");
test.getData();
return 0;
}
Output
The string is: This is a test for variable shadowing!
Example-2:
#include <iostream>
using namespace std;
class Employee
{
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void)
{
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of
Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of
Employee
e1.display();
e2.display();
return 0;
}
Example-3:
#include <iostream>
using namespace std;
class Student
{
public:
int roll_no;
string name;
float marks;
Student(int x, string y, float z)
{
this->roll_no = x;
this->name = y;
this->marks = z;
}
void show()
{
cout<<"Student Name "<<roll_no<<endl;
cout<<"Student Roll "<<name<<endl;
cout<<"Student Marks "<<marks<<endl;
}
};
int main(void)
{
Student stu =Student(102, "Shishir",90);
stu.show();
return 0;
}
Example:
//example of this keyword
class Student
{
int id;
String name;
student(int id,String name)
{
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}
}
Class MyPgm
{
public static void main(String args[])
{
Student s1 = new Student(111,"Anoop");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
Output111 Anoop
222 Aryan
Use Case 2: Accessing Member Variables
The ‘this’ pointer can be also used to access member functions and
variables inside a class. If we have to refer to another member function of a
class inside another class member function, we use the ‘this’ pointer. The
syntax and the example are given below.
Syntax
void demoFunction1()
{
};
void demoFunction2() {
this->demoFunction1();
}
From the syntax, note that the variable that is being referenced using the
‘this’ keyword is the class member variable and the other one is the
parameter variable that is available only locally.
Example
#include <iostream>
using namespace std;
class Test
{
public:
//this is a public class member variable
string testString;
//non-static member function
void setData(string testString)
{
//this is refering to the class member variable
this->testString = testString;
}
void getAndPrint(string str)
{
//accessing both member variables and functions using this pointer
this->setData(str);
cout << "The string is: " << this->testString << endl;
}
};
int main()
{
//create the object
Test test;
//call the member function
test.getAndPrint("This is a test for member accession!");
return 0;
}
Output
The string is: This is a test for member accession!
Use Case 3: Accessing Objects
We can use the ‘ this’ keyword to access
the objects that are currently in memory and can further manipulate them,
we will delete the current object using a member function with the help of
the ‘this’ pointer.
Syntax
void demoFunction()
{
delete this;
}
Example
#include <iostream>
using namespace std;
class Test
{
public:
//this is a public class member variable
string testString;
//non-static member function
void setData(string testString)
{
//this is refering to the class member variable
this->testString = testString;
}
void getAndPrint(string str)
{
//accessing both member variables and functions using this pointer
this->setData(str);
cout << "The string is: " << this->testString << endl;
}
void delObject()
{
//accessing the current object and deleting it
delete this;
}
};
int main()
{
//create the object
Test test;
//call the member function
test.getAndPrint("This is a test for accessing objects!");
test.delObject();
test.getAndPrint("This is a test for accessing objects!");
return 0;
}
Output(Error)
The string is: This is a test for accessing objects!
munmap_chunk(): invalid pointer
timeout: the monitored command dumped core
sh: line 1: 321122 Aborted /usr/bin/timeout 10s main
In this example, we deleted the current object using the ‘this’ pointer, and
then again tried to use the ‘getAndPrint()’ function normally. We can see
that it raises a ‘Segmentation Fault’ error when it is run, as the object has
been deleted from the memory.

You might also like