views:

125

answers:

4

Hello, I have a class A containing two pointers to objects of another class B. I want to initialize one pointer or the other depending on which one is passed to init(), which also takes other parameters. My situation is thus the following:

class A {

public:
    A();
    init(int parameter, int otherParameter, B* toBeInitialized);

protected:
    B* myB;
    B* myOtherB;

};

Now my point is that I want to call init() as:

init(640, 480, this->myB);

or

init(640, 480, this->myOtherB);

Now, my init is implemented as:

void init( int parameter, int otherParameter, B* toBeInitialized ) {

    toBeInitialized = someConstructorFunction(parameter, otherParameter);

}

The problem is that the two pointers are not initialized, I suspect that toBeInitialized is overwritten, but the original parameter is not modified.

I am doing something wrong? Should I use references to pointers?

Thank you
Tommaso

+6  A: 

Yes, change to

void init( int parameter, int otherParameter, B*& toBeInitialized ) {

    toBeInitialized = someConstructorFunction(parameter, otherParameter);

}

In your original code toBeInitialized is passed by value and only the local copy of the variable will be modified.

Andreas Brinck
+2  A: 

You are passing toBeInitialized by value, so the value modified inside init() is not reflected outside. You need to either pass reference to toBeInitialized pointer or a double pointer. i.e. change init signature to init(int, int, B*&) or init(int,int,B**);

Naveen
+3  A: 

This is obviously a cut-down problem, but as stated would it not be better to have something like this:

class A {

public:
    A();
    B* buildB(int parameter, int otherParameter);

protected:
    B* myB;
    B* myOtherB;

};

Then call the function as

this->myB = buildB(640, 480);

Converting the third parameter to be a reference to (or pointer to) the member would work, but it smells like your design might be wrong.

Andrew Aylett
I know, but actually this method initializes more than one thing, so it is not possible to pass all of them with return.
tunnuz
@tunnuz: Then your design probably needs more work. If you've got multiple sets of members which can be independently initialised, consider splitting them into separate classes.
Andrew Aylett
+1  A: 

Consider using pointers to members. (it will give you a little more safety.)

void A::init(int p1, int p2, B * A::* memberToInit)
{
    this->*memberToInit = SomeConstructorFunc(p1, p2);
}

And the usage would be

myObject.init(480, 620, &A::myB);
Ari