C++ Pointers & Functions Question:

What is pointer to member?

Tweet Share WhatsApp

Answer:

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.

Download C++ Pointers & Functions PDF Read All 32 C++ Pointers & Functions Questions
Previous QuestionNext Question
Can you please explain the difference between an inspector and a mutator?What is smart pointer?