Go Down

Topic: Need Help: Problem with Pointers & passing to functions (Read 566 times) previous topic - next topic

Sev

So, I have a function setDataSource which is designed to take an address of an object as an argument and set up a pointer to it inside a class.  I can't figure out how pass a pointed-to object to it.

That is, I can get this to work:

combinedDataObject data;
foo.setDataSource(&data);

However, I cannot get this to work:

combinedDataObject data;
combinedDataObject *p;
foo.setDataSource(&p);

I get compiler errors -- no matching function for call to 'setDataSource(combinedDataObject**)'

Here's the source for the setDataObject function, which is part of class basicTimerObject.  combinedDataObject is derived from timeObject.

void basicTimerObject::setDataSource(timeObject * timeNow)
{
   dataSource = timeNow; // timeObject *dataSource is a protected member of basicTimerObject
}

Any input would be appreciated, thanks!

Delta_G



However, I cannot get this to work:

combinedDataObject data;
combinedDataObject *p;
foo.setDataSource(&p);



Because you are passing a pointer to a pointer there.  If setDataSource expects a pointer then do:

combinedDataObject data;
combinedDataObject *p;
*p = &data;

foo.setDataSource(p);


And then you are passing a pointer to the function that points to data.

Sev

Whoops.  I did make a mistake there, I should have had:

combinedDataObject data;
combinedDataObject *p = &data;
foo.setDataSource(&p);

doesn't work.

setDataSource doesn't expect to be passed a pointer, it expects to be passed the address of an object.  I'm trying to get it to work with a pointer instead.  The problem is that I've got various objects that expect to be passed a reference to the global data object, which they store internally as a pointer, and now I'm trying to use an object which has one of these objects inside of it, along with a reference to the global data object.  I'm trying to initialize the member object with the pointer stored in the object which contains it, rather than by passing it the address directly with &data as it expects.

Sorry if I'm not explaining this well; I have problems with pointers.  %)

WizenedEE


Whoops.  I did make a mistake there, I should have had:

combinedDataObject data;
combinedDataObject *p = &data;
foo.setDataSource(&p);

doesn't work.

Yes. p is a pointer, and &p is the address of the pointer -- a pointer to a pointer. You don't want to have the &, you just want to say
Code: [Select]

foo.setDataSource(p);


Quote
setDataSource doesn't expect to be passed a pointer, it expects to be passed the address of an object.
that's the definition of a pointer

Delta_G

Right, and the pointer is holding the address of an object, &data.  Change the &p to just a p and it will work.

Sev


Go Up