#include"iostream"
class CMessage
{
public:int a;
CMessage(){}
~CMessage(){}
};
void Testing(CMessage *f_pMessage)//l_pMessage is output parameter
{
f_pMessage = new CMessage();
f_pMessage->a = 1;
}
int main()
{
CMessage *l_pMessage =NULL;
Testing(l_pMessage);
std::cout<<l_pMessage->a;//getting l_pMessage = NULL;
return 0;
}
When I called testing then inside testing f_pMessage is getting initialized but as soon as i after excuting testing function it should be store in l_Pmessage but it is showing NULL.confussed.....
Testing(l_pMessage);
At this line, you are passing a copy of the pointer. You either need to pass a pointer to pointer or a reference to pointer:
void Testing(CMessage *& f_pMessage)//l_pMessage is output parameter
{
f_pMessage = new CMessage();
f_pMessage->a = 1;
}
You can do it the other way using a pointer to pointer:
void Testing(CMessage **f_pMessage)//l_pMessage is output parameter
{
*f_pMessage = new CMessage();
(*f_pMessage)->a = 1;
}
But you have to call the function this way:
Testing(&l_pMessage);
Passing by pointer only allows you to modify what is being pointed at. The pointer itself is still being passed by value.
Since you want to change a pointer, you can either pass a pointer to a pointer or take the pointer by reference:
void Testing(CMessage *&f_pMessage)//l_pMessage is output parameter
{
f_pMessage = new CMessage();
f_pMessage->a = 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With