Question: In C++ you can also declare pointers to non-static class members. Both function and data members can be pointed to. The pointers are not really

In C++ you can also declare pointers to non-static class members. Both function and data members can be pointed to. The pointers are not really addresses, though; they are just offsets. In the case of data members, they are just offsets into an object. In the case of member functions, they are offsets into the classs list of functions. The following example illustrates pointers to member functions. Note the necessary parentheses when declaring and accessing a member through a member pointer. This is because a function call has higher precedence than :: or *.

class C

{

public:

void f() {cout

void g() {cout

};

int main()

{

C c;

// Using an object

void (C::*pmf)() = &C::f;

(c.*pmf)(); // Executes c.f()

pmf = &C::g;

(c.*pmf)(); // Executes c.g()

// Using pointer to an object

C* cp = &c;

pmf = &C::f;

(cp->*pmf)(); // Executes cp->f()

pmf = &C::g;

(cp->*pmf)(); // Executes cp->g()

}

Compile and run this program and observe the results. Make sure you understand it. Youll have to include , of course. Make up your own example that uses pointers to data members.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!