Pointers in C++
0 3548
In C++, constructors and every member functions except static member function receive a hidden implicit parameter that is known as this pointer. This keyword is a special keyword found in C++ programming language that is used to represent the current object.
At the time of function call, the object invoking that function is known as a current object. This is one type of pointer that is used to store current object address.
For example
If we are calling the following object i.e. Obj2.function (); then this pointer holds the current object address. The value of this pointer will be set as the value of obj2. In every no static member function, this process act as the hidden argument automatically passed. This function can be used as in an explicit way also. As shown below
class website
{
void code();
{
}
};
website k;
k.code(); \\this pointer value is the current object values
This pointer can also be used as a local variable can be used in no static member function body and can be used as an explicit way as explained in the following example.
class website
int b;
public:
void code()
{
This->b=400;// use of this pointer in an explicit way
}
};
This pointer can be used in the following way
Implicit way
Explicit way
this->b=400; or (this).b=400;
This pointer holds the current address of the current object through which the specific function is invoked. It is available in all no static member functions and absent in static member function and friend function. This Pointer can be used for the following three reasons
* Returning values from the member function
* Accessing member functions
* Specifying memory address
A simple program illustrating this pointer in C++ Programming Language
#include <iostream>
using namespace std;
class website {
private:
int code;
char ch;
public:
void setMyValues(int code, char ch){
this->code =code;
this->ch=ch;
}
void displayValues(){
cout<<code<<endl;
cout<<ch;
}
};
int main(){
website k;
k.setMyValues(400, 'B');
k.displayValues();
return 0;
}
Output
400
B
Share:
Comments
Waiting for your comments