ClassA* pa = NULL;
ClassA* pb = NULL;
void assignObject(ClassA* pa, ClassB* pb)
{
pa = new ClassA;
pb = new ClassB;
}
What will be the value of pa
and pb
after executing the function?
EDIT how to pass as pointer is the return if pa,pb is NULL
As pointed out in other answers - both will still be NULL after the call. However, there are two possible solutions to this problem:
1) references
void assignObject(ClassA*& pa, ClassB*& pb)
{
pa = new ClassA;
pb = new ClassB;
}
ClassA* pa = NULL;
ClassA* pb = NULL;
assignObject(pa, pb); // both will be assigned as expected.
2) pointers
void assignObject(ClassA** pa, ClassB** pb)
{
assert(pa != NULL); assert(pb != NULL);
*pa = new ClassA;
*pb = new ClassB;
}
ClassA* pa = NULL;
ClassA* pb = NULL;
assignObject(&pa, &pb); // both will be assigned as expected.
Most programmers would probably choose references because then they don't need to assert anything (references can never be NULL).
They will be NULL, since you're passing them by value. If you want to pass it by reference, you'd do this:
ClassA* pa = NULL;
ClassA* pb = NULL;
assignObject(ClassA*& pa, ClassB*& pb)
{
pa = new ClassA;
pb = new ClassB;
}
Note, I'm not sure what you're trying to accomplish with the global variables. They're never used in this example, since the local variables (function parameters) hide them.
I think you also need to declare a return value type for your function in order for it to be valid C++.
ClassA* pa = NULL;
ClassA* pb = NULL;
void assignObject(ClassA* &pa,ClassB* &pb)
{
pa = new ClassA;
pb = new ClassB;
}
Alternatively:
ClassA* pa = NULL;
ClassA* pb = NULL;
void assignObject(ClassA** pa,ClassB** pb)
{
*pa = new ClassA;
*pb = new ClassB;
}
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