Interview Questions Answers.ORG
Interviewer And Interviewee Guide
Interviews
Quizzes
Home
Quizzes
Interviews C Plus Plus Language Interviews:C++ Access ControlC++ COM ActiveXC++ ConstructorsC++ ContainersC++ Exception HandlingC++ FriendC++ InheritanceC++ Inline FunctionC++ New And DeleteC++ Operator OverloadingC++ Pointers & FunctionsC++ ProgrammerC++ ReferencesC++ Static DataC++ SyntaxC++ TemplateC++ Type CheckingC++ Virtual Functions
Copyright © 2018. All Rights Reserved
C++ Pointers & Functions Interview Question:
What is pointer to member?
Submitted by: Administratornot 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.
Submitted by: Administrator
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.
Submitted by: Administrator
Copyright 2007-2024 by Interview Questions Answers .ORG All Rights Reserved.
https://InterviewQuestionsAnswers.ORG.
https://InterviewQuestionsAnswers.ORG.