C++ Object Class this Pointer
Syntax
The this
pointer is a keyword in C++ which always refers to the current object. The syntax to use the this
pointer in a class method is as follows:
type class_name::method_name() {
// code using `this` pointer
}
Example
Let's take an example of a Person
class that has two private member variables name
and age
. We will define a method printDetails()
that will print out the details of the current object using the this
pointer.
class Person {
private:
string name;
int age;
public:
Person(string n, int a) {
name = n;
age = a;
}
void printDetails() {
cout << "Name: " << this->name << endl;
cout << "Age: " << this->age << endl;
}
};
int main() {
Person person1("John Doe", 30);
person1.printDetails();
return 0;
}
Output
Name: John Doe
Age: 30
Explanation
In the printDetails()
method, we are using the this
pointer to access the name
and age
member variables of the current object. The ->
operator is used to access the member variables through the this
pointer.
Use
The this
pointer is used in class methods to access the member variables and methods of the current object. It is especially useful when there are local variables with the same names as the member variables, as it helps to avoid naming conflicts and ambiguity.
Important Points
- The
this
pointer is a keyword in C++ which always refers to the current object. - It is used in class methods to access the member variables and methods of the current object.
- The
->
operator is used to access the member variables through thethis
pointer.
Summary
The this
pointer is a powerful feature of C++ that allows class methods to access the member variables and methods of the current object. It is a keyword that always refers to the current object and can be used to avoid naming conflicts and ambiguity.