Pointers to Members

  • Thread starter Christian Nolte
  • Start date
C

Christian Nolte

I want to implement dynamic calling of interface methods using pointers to
members and have some trouble to get it right. An example of what I am
talking about looks like that:

///////////////////////////////////////////////
class StdInterface {
public:
int func(void) {return 1;}
int func2(void) {return 2;}
};

typedef int (StdInterface::*fp)();

class UseInterface {
public:
fp m_func;
};
///////////////////////////////////////////////

The next code excerpt shows how I want to use the pointer to meber:

///////////////////////////////////////////////
UseInterface *a = new UseInterface();
StdInterface *b = new StdInterface();

std::cout << b->func();
a->m_func = &StdInterface::func;

// here the compiler error C2065: 'm_func': not declared occurs (MS VC
..net):
std::cout << (a->*m_func)();
///////////////////////////////////////////////

Why does the compiler complain here? I have found an example of how to use a
pointer to member in Stroustrup (15.5 - Pointers to Members):

///////////////////////////////////////////////
//Example : Stroustrup (15.5 : Pointers to Members)

typedef int (StdInterface::*Pstd_mem)(); // pointer to member type

void f(StdInterface* p)
{
Pstd_mem s = &StdInterface::func;
//p->func(); // direct call
std::cout << (p->*s)() ; // call through pointer to member
}
////////////////////////////////////////////////

The above code works fine while mine is somehow wrong and I don't have a
clue on how to fix it. The only difference is, that my pointer is inside a
class, while the pointer in Stroustrups example is somehow
"function-scoped"...

Any help would be very much appreciated!
 
D

David Harmon

I want to implement dynamic calling of interface methods using pointers to
members and have some trouble to get it right.

For a start, see section "[33] Pointers to member functions" in Marshall
Cline's C++ FAQ. It is always good to check the FAQ before posting.
You can get the FAQ at:
http://www.parashift.com/c++-faq-lite/
// here the compiler error C2065: 'm_func': not declared occurs (MS VC
.net):
std::cout << (a->*m_func)();

Invoking the function requires an instance of class StdInterface.
b->*

m_func is a ordinary member of class UseInterface.
a->m_func

Put them together
b->*(a->m_func)()
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top