this
is a keyword that represents a pointer to the current object instance. It is a special pointer that is automatically created and initialized by the compiler for each member function of a class.
When a member function is called on an object, the this
pointer points to the memory address of that object. The this
pointer can be used to access member variables and member functions of the current object, as well as to return a reference to the current object.
#include <iostream>
using namespace std;
class First{
private:
string name;
public:
void setName(string x) {
this->name = x;
}
void getName() {
cout << "Name: " << name << endl;
}
};
int main() {
First Object;
Object.setName("Slavoj Zizek");
Object.getName();
return 0;
}
this
is a keyword that refers to the current object. The this
keyword is used to disambiguate between the local parameter variable name
and the class data member name
.
In the setName
function, this->name
refers to the name
data member of the current object. This is used to set the value of the name
data member of the current object to the value passed to the function as the parameter.
In this way, this
helps to differentiate between the local variable name
and the class member name
which have the same name.
No comments:
Post a Comment