2006 Outside Delhi:
2.a. What is “this” pointer? Give an example to illustrate the use of it in C++.
Ans. A special pointer known as this pointer stores the address of the object that is currently invoking a member function. The this pointer is implicitly passed to the member functions of a class whenever they are invoked.
(As soon as you define a class, the member functions are created and placed in the memory space only once. That is, only one copy of member functions is maintained that is shared by all the objects of the class.
Only space for data members is allocated separately for each object.
When a member function is called, it is automatically passed an implicit(in built) argument that is a pointer to the object that invoked the function. This pointer is called this. If an object is invoking a member function, then an implicit argument is passed to that member function that points to (that) object. The programmer also can explicitly specify ‘this’ in the program if he desires.)
Eg: Example program to demonstrate the usage of this pointer.
#include<iostream.h>
#include<conio.h>
class Rectangle
{
float area,len,bre;
public:
void input( )
{
cout<<"\nEnter the length and breadth: ";
cin>>this->len>>this->bre;
}
void calculate( )
{
area=len*bre;//Here Implicit 'this' pointer will be worked.
}
void output( )
{
cout<<"\nThe Area of the Rectangle: "<<this->area;
}
};
void main( )
{
Rectangle R;
clrscr( );
R.input( );
R.calculate( );
R.output( );
getch();
}
2004
1.d. What will be the output of the following program:
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
void ChangeString(char Text[],int &Counter)
{
char *Ptr=Text;
int Length=strlen(Text);
for(;Counter<Length-2;Counter+=2,Ptr++)
{
*(Ptr+Counter)=toupper(*(Ptr+Counter));
}
}
void main( )
{
clrscr( );
int Position=0;
char Message[]=”Pointers Fun”;
ChangeString(Message,Position);
cout<<Message<<”@”<<Position;
}