Scope Resolution Operator Versus this pointer in C++?


Here we will see some C++ examples and try to get what type of output will generate. Then we can understand the purpose and functions of scope resolution operator and the ‘this’ pointer in C++.

If some code has some members say ‘x’, and we want to use another function that takes an argument with the same name ‘x’, then in that function, if we use ‘x’, it will hide the member variable, and local variable will be used. Let us check this in one code.

Example

 Live Demo

#include <iostream>
using namespace std;
class MyClass {
   private:
      int x;
   public:
      MyClass(int y) {
         x = y;
      }
   void myFunction(int x) {
      cout << "Value of x is: " << x;
   }
};
main() {
   MyClass ob1(10);
   ob1.myFunction(40);
}

Output

Value of x is: 40

To access the x member of the class, we have to use the ‘this’ pointer. ‘this’ is a special type of pointer that points to the current object. Let us see how ‘this’ pointer helps to do this task.

Example

 Live Demo

#include <iostream>
using namespace std;
class MyClass {
   private:
      int x;
   public:
      MyClass(int y) {
         x = y;
      }
   void myFunction(int x) {
      cout << "Value of x is: " << this->x;
   }
};
main() {
   MyClass ob1(10);
   ob1.myFunction(40);
}

Output

Value of x is: 10

In C++, there is another operator called scope resolution operator. That operator is used to access member of parent class or some static members. If we use the scope resolution operator for this, it will not work. Similarly, if we use the ‘this’ pointer for static member, it will create some problems.

Example

 Live Demo

#include <iostream>
using namespace std;
class MyClass {
   static int x;
   public:
      void myFunction(int x) {
         cout << "Value of x is: " << MyClass::x;
      }
};
int MyClass::x = 50;
main() {
   MyClass ob1;
   ob1.myFunction(40);
}

Output

Value of x is: 50

Updated on: 30-Jul-2019

185 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements