6.
this pointer using class
In C++ programming, "this" is a keyword representing the current class instance.
It serves three primary purposes: passing the current object as a parameter to another method,
referring to current class instance variables, and declaring indexers.
The "this" pointer is automatically passed as a hidden argument in non-static member function
calls.
#include<iostream>
using namespace std;
class Coordinate {
private:
int x;
int y;
public:
Coordinate (int x, int y) {
// Using this pointer inside the constructor
// to set values in data members.
this->x = x;
this->y = y;
}
void printCoordinate() {
cout<<"(x, y) = ("<<this->x<<", "<<this->y<<")"<<endl;
}
};
int main () {
// Passing x and y coordinate in the constructor.
Coordinate pointA(2, 3), pointB(5, 6);
// Pointing the coordinates.
pointA.printCoordinate();
pointB.printCoordinate();
return 0;
}
Output
(x, y) = (2, 3)
(x, y) = (5, 6)