Pointers question (passing pointer to another function)

A

A

Hi,

I'd like to do something very simple but I'm not sure if I'm doing it right:

I have 2 functions:

//------------
void Function1(TObject *obj)
{
Function2(obj);
}

void Function2(TObject *obj)
{
obj->CallSomeObjFunction();
}
//------------

So basically Function1 simply calls Function2 and passes pointer to use it
in Function2.

The above code compiles and works, but I'm not sure about the scopes of obj
pointer and if it can be used like this?

Is the above usage of pointer correct or should I use &obj instead?
 
A

Alf P. Steinbach

Hi,

I'd like to do something very simple but I'm not sure if I'm doing it right:

I have 2 functions:

//------------
void Function1(TObject *obj)
{
Function2(obj);
}

void Function2(TObject *obj)
{
obj->CallSomeObjFunction();
}
//------------

So basically Function1 simply calls Function2 and passes pointer to use it
in Function2.

The above code compiles and works, but I'm not sure about the scopes of obj
pointer and if it can be used like this?

Is the above usage of pointer correct or should I use&obj instead?

Technically it's correct.

Design-wise, though, in both functions the code assumes that the passed in
pointer will be valid and non-null.

That's best expressed in the language itself, by using references instead of
pointers:


void function2( Object& o )
{
o.someObjFunction();
}

void function1( Object& o )
{
function2( o );
}

int main()
{
Object blah;
function1( blah );
}


Regarding scopes you're OK.


Cheers & hth.,

- Alf (blatant plug: my new (first) blog at <url: http://alfps.wordpress.com/>)
 
A

A

Design-wise, though, in both functions the code assumes that the passed in
pointer will be valid and non-null.

I understand what you mean, but that part should be ok. because in first
function object is defined and non-null (and its pointer is passed as
input).
I simply use second function to have a sort of template (a lot of code that
would otherwise be repeated identically in several functions):
like this example:

functionTemplate(object *obj, int iParamThatDiffers)
{
// do a lot of stuff here that is identical for functionA, functionB,
functionC

// Do obj specific stuff with param
obj->DoStuffThatRequiresObj(iParamThatDiffers);
}

and then

functionA(object *obj)
{
functionTemplate(obj, 1);
}

functionB(object *obj)
{
functionTemplate(obj, 2);
}

functionC(object *obj)
{
functionTemplate(obj, 3);
}

So I was mainly concerned about the scope of obj if I move it to other
function like that.

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top