C++:pointers| this pointer

Difference between object pointer and this pointer

 

Object Pointer this pointer

The pointer pointing to object are called as object pointer

Student *p=new student();

When a member function is called , it automatically passes an implicit argument that is a pointer to the invoking object. The automatic pointer used to invoke objects is called as “this” pointer

 

It is useful in creating object at run time

Cout<<”enter total students”;
Cin>>n;
Student *p=new student[n];

It is useful when we compare two or more objects inside a member function and return the invoking object as a result.
we can also use an object pointer to access the public member of an object. We can use a “this” pointer whenever a member function must utilize a pointer to the object that invoked it.

Example:1
Write a C++ program to declare a class named person with attributes as name and age. Take input for details of two person check and print the details of the elder person.
Sol:

#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
class person
{
private:
	char name[20];
	int age;
public:
	person(); //default cons
	person(char *n,int a); //para cons
	void read();
	void show();
	person elder(person p);
};
//defa cons
person::person()
{
  name[0]='\0';
  age=0;
}
//para cons
person::person(char *n,int a)
{
  strcpy(name,n);
  age=a;
}
void person::read()
{
  cout<<"Enter name and age ";
  cin>>name>>age;
}
void person::show()
{
  cout<<"name "<<name<<" age "<<age<<endl;
}
person person::elder(person p)
{
  if(age>p.age) //if(this->age>p.age)
  return(*this);
  else
  return(p);
}
/*

*this represents the object using which the member function
is called.

*/
int main()
{
	//person p1("mohit",26);
  	//person p2("sumit",18);
  	person p1,p2;
  	p1.read(); p2.read();
  	person p3;
  	p3=p1.elder(p2);
  	p3.show();
  	getch();
  	return(0);
}


Output:

Enter name and age mohit
15
Enter name and age kapil
14
name mohit age 15