Question

ClassA* pa = NULL;
ClassA* pb = NULL;
assignObject(ClassA* pa,ClassB* pb)
{
pa = new ClassA;
pb = new ClassB;
}

what will be the value of pa,pb after executing the function

EDIT how to pass as pointer is the return if pa,pb is NULL

Was it helpful?

Solution

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

OTHER TIPS

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;
}

NULL, because you're passing the pointers in by value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top