

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
#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
#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
- Related Questions & Answers
- Scope Resolution Operator vs this pointer in C++
- C++ Scope resolution operator
- Scope resolution operator in C++
- PHP Scope Resolution Operator (::)
- What is the scope resolution operator in C#?
- Why does C++ need the scope resolution operator?
- Where do we use scope Resolution Operator (::) in C#?
- What is the use of scope resolution operator in C++?
- What is Pointer operator * in C++?
- What is pointer operator & in C++?
- Double Pointer (Pointer to Pointer) in C
- Python Pandas - Return a new Timedelta ceiled to this resolution
- Python Pandas - Return a new Timedelta floored to this resolution
- calloc() versus malloc() in C
- For Versus While in C++