Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment inside function that is passed as pointer?

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

like image 815
yesraaj Avatar asked Jan 06 '09 11:01

yesraaj


3 Answers

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

like image 159
Paulius Avatar answered Oct 08 '22 13:10

Paulius


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

like image 4
Zach Hirsch Avatar answered Oct 08 '22 15:10

Zach Hirsch


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;
}
like image 2
mmx Avatar answered Oct 08 '22 14:10

mmx