...
Here's an example of using this
inside a member function:
Code Block | ||
---|---|---|
| ||
//Simple example of a class called MyClass class MyClass { public: void printAddress() { cout << "Object address: " << this << endl; } }; //main program to demo the MyClass int main() { MyClass obj; obj.printAddress(); return 0; } |
Here's an example of using this
inside a class:
Code Block | ||
---|---|---|
| ||
//Simple example of a class called MyClass class MyClassTwo { private: int x; public: MyClassMyClassTwo(int x) { this->x = x; } void printX() { cout << "x = " << this->x << endl; } }; int main() { MyClassMyClassTwo objmyObj(42); objmyObj.printX(); return 0; } |
In this example, we have defined a class MyClass
with a private member x
. The constructor of the class takes an integer argument and assigns it to the x
member using this->x
. The printX
member function then prints the value of x
using this->x
.
...