0% found this document useful (0 votes)
0 views

EXP-6 This pointer using class

In C++, the 'this' pointer refers to the current class instance and has three main uses: passing the current object to methods, accessing instance variables, and declaring indexers. The provided code demonstrates the use of 'this' in a class constructor to initialize member variables and in a method to print the coordinates. The output shows the coordinates of two instances of the Coordinate class.

Uploaded by

shiv.prasad2049
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

EXP-6 This pointer using class

In C++, the 'this' pointer refers to the current class instance and has three main uses: passing the current object to methods, accessing instance variables, and declaring indexers. The provided code demonstrates the use of 'this' in a class constructor to initialize member variables and in a method to print the coordinates. The output shows the coordinates of two instances of the Coordinate class.

Uploaded by

shiv.prasad2049
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

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)

You might also like