Here is a listing of C++ language interview questions on “Pointers to Members” along with answers, explanations and/or solutions:
1. Which is referred by pointers to member?
a) Static members of class objects
b) Non-static members of class objects
c) Referring to whole class
d) Dynamic members of class objects
Answer: b
Clarification: We cannot use a pointer to member to point to a static class member because the address of a static member is not associated with any particular object.
2. What should be used to point to a static class member?
a) Smart pointer
b) Dynamic pointer
c) Normal pointer
d) Static pointer
Answer: c
Clarification: Normal pointer is sed to point to a static class member.
3. Which operator is used in pointer to member function?
a) .*
b) ->*
c) Both .* & ->*
d) $*
Answer: c
Clarification: The pointer to member operators .* and ->* are used to bind a pointer to a member of a specific class object.
4. What will be the output of the following C++ code?
-
#include
-
using namespace std;
-
class X
-
{
-
public:
-
int a;
-
void f(int b)
-
{
-
cout<< b << endl;
-
}
-
};
-
int main()
-
{
-
int X :: *ptiptr = &X :: a;
-
void (X :: * ptfptr) (int) = &X :: f;
-
X xobject;
-
xobject.*ptiptr = 10;
-
cout << xobject.*ptiptr << endl;
-
(xobject.*ptfptr) (20);
-
}
a)
10 20
b)
20 10
c) 20
d) 10
Answer: a
Clarification: In this program, We are assigning 10 and printing it in the
main function and then for value 20, We are passing the value to class and
printing it.
Output:
$ g++ ptm.cpp $ a.out 10 20
5. What will be the output of the following C++ code?
-
#include
-
using namespace std;
-
class Testpm
-
{
-
public:
-
void m_func1()
-
{
-
cout << "func1n";
-
}
-
int m_num;
-
};
-
void (Testpm :: *pmfn)() = &Testpm :: m_func1;
-
int Testpm :: *pmd = &Testpm :: m_num;
-
int main()
-
{
-
Testpm ATestpm;
-
Testpm *pTestpm = new Testpm;
-
(ATestpm.*pmfn)();
-
(pTestpm ->* pmfn)();
-
ATestpm.*pmd = 1;
-
pTestpm ->* pmd = 2;
-
cout << ATestpm.*pmd << endl
-
<< pTestpm ->* pmd << endl;
-
}
a) func1
b)
func1 func1
c)
1 2
d)
func1 func1 1 2
View Answer
Clarification: In this program, As we are passing the value twice to the method
in the class, It is printing the func1 twice and then it is printing the given
value.
Output:
$ g++ ptm1.cpp $ a.out func1 func1 1 2
6. What will be the output of the following C++ code?
-
#include
-
using namespace std;
-
class Car
-
{
-
public:
-
int speed;
-
};
-
int main()
-
{
-
int Car :: *pSpeed = &Car :: speed;
-
Car c1;
-
c1.speed = 1;
-
cout << c1.speed << endl;
-
c1.*pSpeed = 2;
-
cout << c1.speed << endl;
-
return 0;
-
}
a) 1
b) 2
c) Both 1 & 2
d) 4
Answer: c
Clarification: In this program, We are printing the value by direct access and another one by using pointer to member.
Output:
$ g++ ptm2.cpp $ a.out 1 2