Interview Questions Answers.ORG
Interviewer And Interviewee Guide
Interviews
Quizzes
Home
Quizzes
Interviews C Plus Plus Language Interviews:C++ Access ControlC++ COM ActiveXC++ ConstructorsC++ ContainersC++ Exception HandlingC++ FriendC++ InheritanceC++ Inline FunctionC++ New And DeleteC++ Operator OverloadingC++ Pointers & FunctionsC++ ProgrammerC++ ReferencesC++ Static DataC++ SyntaxC++ TemplateC++ Type CheckingC++ Virtual Functions
Copyright © 2018. All Rights Reserved
C++ Pointers & Functions Interview Question:
Can you please explain the use of this pointer?
Submitted by: AdministratorWhen a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object (ie the object on which the function is invoked). This pointer is known as this pointer. It is internally created at the time of function call.
The this pointer is very important when operators are overloaded.
Example: Consider a class with int and float data members and overloaded Pre-increment operator ++:
class MyClass
{
int i;
float f;
public:
MyClass ()
{
i = 0;
f = 0.0;
}
MyClass (int x, float y)
{
i = x; f = y;
}
MyClass operator ++()
{
i = i + 1;
f = f + 1.0;
return *this; //this pointer which points to the caller object
}
MyClass show()
{
cout<<”The elements are:n” cout<i<<”n<f; //accessing
data members using this
}
};
int main()
{
MyClass a;
++a; //The overloaded operator function ++()will return a's this
pointer
a.show();
retun 0;
}
The o/p would be:
The elements are:
1
1.0
Submitted by: Administrator
The this pointer is very important when operators are overloaded.
Example: Consider a class with int and float data members and overloaded Pre-increment operator ++:
class MyClass
{
int i;
float f;
public:
MyClass ()
{
i = 0;
f = 0.0;
}
MyClass (int x, float y)
{
i = x; f = y;
}
MyClass operator ++()
{
i = i + 1;
f = f + 1.0;
return *this; //this pointer which points to the caller object
}
MyClass show()
{
cout<<”The elements are:n” cout<i<<”n<f; //accessing
data members using this
}
};
int main()
{
MyClass a;
++a; //The overloaded operator function ++()will return a's this
pointer
a.show();
retun 0;
}
The o/p would be:
The elements are:
1
1.0
Submitted by: Administrator
Copyright 2007-2024 by Interview Questions Answers .ORG All Rights Reserved.
https://InterviewQuestionsAnswers.ORG.
https://InterviewQuestionsAnswers.ORG.