cpp :pointers 17

“this” pointer

• “this” pointer is a special pointer variable which stores the address of the object itself. i.e. it points to the object itself.

• “this” pointer is present for all the objects.

• “this” pointer is present in all the members functions, we may or may not make use of it.(till now we have not used it.)

Example:1
Write a C++ program to declare a class named student with attributes as roll number, student name, and per. Take input for the details and display them.
Sol:

#include<iostream>
#include<conio.h>
using namespace std;
class student
{
private:
	int roll;
	char name[20];
	float age;
public:
	void read();
	void show();
};
void student::read()
{
	cout<<"Address of obejct is "<<this<<endl;
   	cout<<"Enter roll , name and age  ";
   	cin>>this->roll>>this->name>>this->age;
}
void student::show()
{
	cout<<"Address of obejct is "<<this<<endl;
	cout<<this->roll<<" "<<this->name<<" "<<age<<endl;
}
int main()
{
  student s1,s2;
  s1.read();s2.read();
  s1.show();s2.show();
  getch();
  return(0);
}

Output:

Address of obejct is 0x6ffe00
Enter roll , name and age 101
arun
25
Address of obejct is 0x6ffde0
Enter roll , name and age 102
komal
16
Address of obejct is 0x6ffe00
101 arun 25
Address of obejct is 0x6ffde0
102 komal 16

Example:2
Write a C++ program to declare a class named employee with attributes as employee number, employee name, and basic salary. Take input for the details and display them.
Sol:

#include<iostream>
#include<conio.h>
using namespace std;
class employee
{
     private:
          int empno;
          char name[20];
          float sal;
     public:
          void read();
          void show();
};
void employee::read()
{
	cout<<"Address of obejct is "<<this<<endl;
    cout<<"Enter empno, name and salary ";
    cin>>this->empno>>this->name>>this->sal;
}
void employee::show()
{
	cout<<"Address of obejct is "<<this<<endl;
    cout<<"empno "<<this->empno<<" name "<<this->name<<" sal "<<this->sal<<endl;
}
int main()
{
    employee e1,e2;
    e1.read(); e2.read();
    e1.show(); e2.show();
    return(0);
     
}

Output:

Address of obejct is 0x6ffe00
Enter empno, name and salary 101
kapil
45000
Address of obejct is 0x6ffde0
Enter empno, name and salary 102
mohit
65000
Address of obejct is 0x6ffe00
empno 101 name kapil sal 45000
Address of obejct is 0x6ffde0
empno 102 name mohit sal 65000