0

Actually I am new to writing handlers but somehow i managed to write this piece of code:

#include<iostream>

using namespace std;

class test
{
public:
typedef void (test::*MsgHandler)(int handle);

test()
{
    cout<<"costructor called"<<endl;
}

void Initialize()
{
    add_msg_Handler(4,&test::System);
}

void System(int handle)
{
    cout<<endl<<"Inside System()"<<endl;
    cout<<"handle:"<<handle<<endl;
}

protected:
MsgHandler message[20];
void add_msg_Handler(int idx,MsgHandler handler)
{
    cout<<endl<<"Inside add_msg_Handler()"<<endl;
    cout<<"handler:"<<handler<<endl;
    message[idx]=handler;
    cout<<"message:"<<message[idx]<<endl;
}
};

int main()
{
test obj;
obj.Initialize();

return 0;
}

This code is working fine, I get the output as:

costructor called

Inside add_msg_Handler()
handler:1
message:1

But there are several things beyond my scope. If I am right System() should have been called in this line:

add_msg_Handler(4,&test::System);

but this is not happening. I need help on rectifying this.

Second thing is, I am not able to understand why I am getting such output:

handler:1

I mean how does handler got initialized to 1.Can somebody help me in solving this??

NixiN
  • 83
  • 9

1 Answers1

8

&test::System is not a function call, it's a pointer to the member function test::System.
(A call would look like System(0) and wouldn't compile if you used it as the parameter in question.)

If you look at the definition of add_msg_handler:

cout<<endl<<"Inside add_msg_Handler()"<<endl;
cout<<"handler:"<<handler<<endl;
message[idx]=handler;
cout<<"message:"<<message[idx]<<endl;

there's not a single place that calls the function handler.
(A call would look like (this->*handler)(0) or (this->*message[idx])(0).)

So the function isn't called because there's nothing in your code that calls it.

The output is 1 because

  • handler is a pointer to a member function
  • there's no overload of << for pointers to member functions
  • there is an implicit conversion from pointer to member function to bool
  • there's an overload of << for bool
  • a non-null pointer is implicitly converted to true
  • true outputs as 1 by default.
molbdnilo
  • 64,751
  • 3
  • 43
  • 82