• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests

C++ this pointer

Question 1

Which of the following is true about this pointer?
  • It is passed as a hidden argument to all function calls
  • It is passed as a hidden argument to all non-static function calls
  • It is passed as a hidden argument to all static functions
  • None of the above

Question 2

What is the use of this pointer?
  • When local variable’s name is same as member’s name, we can access member using this pointer.
  • To return reference to the calling object
  • Can be used for chained function calls on an object
  • All of the above

Question 3

Predict the output of following C++ program. C
#include<iostream>
using namespace std;

class Test
{
private:
  int x;
public:
  Test(int x = 0) { this->x = x; }
  void change(Test *t) { this = t; }
  void print() { cout << \"x = \" << x << endl; }
};

int main()
{
  Test obj(5);
  Test *ptr = new Test (10);
  obj.change(ptr);
  obj.print();
  return 0;
}
  • x = 5
  • x = 10
  • Compiler Error
  • Runtime Error

Question 4

Predict the output of following C++ program CPP
#include<iostream>
using namespace std;

class Test
{
private:
  int x;
  int y;
public:
  Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
  static void fun1() { cout << \"Inside fun1()\"; }
  static void fun2() { cout << \"Inside fun2()\"; this->fun1(); }
};

int main()
{
  Test obj;
  obj.fun2();
  return 0;
}
  • Inside fun2() Inside fun1()
  • Inside fun2()
  • Inside fun1() Inside fun2()
  • Compiler Error

Question 5

Predict the output of following C++ program? CPP
#include<iostream>
using namespace std;

class Test
{
private:
  int x;
public:
  Test() {x = 0;}
  void destroy()  { delete this; }
  void print() { cout << \"x = \" << x; }
};

int main()
{
  Test obj;
  obj.destroy();
  obj.print();
  return 0;
}
  • x = 0
  • undefined behavior
  • compiler error

There are 5 questions to complete.

Last Updated :
Take a part in the ongoing discussion