views:

191

answers:

4
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

A: 

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

Roddy
how to pass as pointer
yesraaj
Maybe you should change the question...?
Roddy
+1  A: 
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;
}
Mehrdad Afshari
+2  A: 

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

Zach Hirsch
the sample is just an example
yesraaj
@rajKumar: make sure you post valid code; otherwise, you can end up with misleading or even incorrect answers.
Jonathan Leffler
+4  A: 

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

Paulius Maruška