What is pointer to member? - C++

What is pointer to member?

- Not to a specific instance of that member in an object. This type of pointer is called a pointer to a class member or a pointer-to-member. It is not same as normal C++ pointer. Instead it provides only an offset into an object of the member’s class at which that member can be found. Since member pointers are not true pointers, the . and → can not be applied to them. Instead we must use the special operators .* and →* . They allow access to a member of a class.
- Example :
#include <iostream>
using namespace std;
class MyClass
{
   public:
       int val;
       MyClass(int i)
       {
          val = i;
       }
       int double_val()
       {
          return val + val;
       }
};

int main()
{
   int MyClass::*data;   //data member pointer
   int(MyClass::*func)();   //function member pointer
   MyClass obj1(1), obj2(2);   //create objects
   data =&MyClass::val;   //get offset of data val
   func=&MyClass::double_val;   //get offset of function double_val()

   cout << “The values are:”;
   cout << ob1.*data << “ “ << ob2.*data << “\n”;
   cout << “Here they are doubled:”;
   cout << (ob1.*func)() << “ “ << (ob2.*func)() << “\n”;

   return 0;
}
- Here data and func are member pointers. As shown in the program, when declaring pointers to members, you must specify the class and use the scope resolution operator.
What is const pointer and const reference? - C++
What is const pointer and const reference? - const pointer is a pointer which you don’t want to be pointed to a different value.....
What is NULL pointer and void pointer and what is their use?
What is NULL pointer and void pointer and what is their use? - A NULL pointer has a fixed reserved value that is not zero or space, which indicates that no object is referred.....
Difference between pass by value and pass by reference - C++
Difference between pass by value and pass by reference - In pass by value approach, the called function creates another copies of the variables passes as arguments.....
Post your comment