Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Professional Android 4 Application Development

Authors: Reto Meier

3rd Edition

1118223853, 9781118223857

More Books

Students also viewed these Programming questions