Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass by pointer is not working

Tags:

c++

#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.....

like image 986
Suri Avatar asked Jan 19 '26 14:01

Suri


2 Answers

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);
like image 147
Khaled Alshaya Avatar answered Jan 22 '26 07:01

Khaled Alshaya


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;
}
like image 25
R Samuel Klatchko Avatar answered Jan 22 '26 05:01

R Samuel Klatchko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!