Sign in to follow this  

pointer stuff

This topic is 4689 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am messing around here, and can't get my head around this...
int main()
{
	Object A;
	Stuff *ptr;
	A.GetPtr( ptr );
	return 0;
}

class Object
{
public:
	Object { m_ptr = new Stuff(2); };
	GetPtr( Stuff *ptr ) { ptr = m_ptr; };
private:
	Stuff *m_ptr;
};

struct Stuff
{
	int a;
}

I want to create a Stuff pointer. somewhere in the code I want to get the objects Stuff pointer ... so my ptr in main is pointing to the Objects Stuff struct. i.e m_ptr and ptr should in the end point to the same Stuff struct ...

Share this post


Link to post
Share on other sites
change

GetPtr( Stuff *ptr ) { ptr = m_ptr; }

to

GetPtr( Stuff *&ptr ) { ptr = m_ptr; }

What was originally happening is a copy of ptr was being passed to the function. You need to pass a refernce to it if you want the changes to effect the original value.

Share this post


Link to post
Share on other sites
Or you could use a Stuff **p pointer (if for any reason you would like to avoid references).
Anyway, you could do the following:

int main()
{
Object A;
Stuff *ptr;
ptr = A.GetPtr();
return 0;
}

class Object
{
public:
Object { m_ptr = new Stuff(2); };
Stuff* GetPtr( Stuff *ptr ) { return m_ptr; };
private:
Stuff *m_ptr;
};

Share this post


Link to post
Share on other sites
IFooBar hit the nail...

It is intentional to pass a pointer as a variable to the function, and have the function alter the pointer.. (so I can use the return to pass error messages instead)

I suspected that was happening, ptr was passed with copy, and thus did not get altered, but I was stuck in how to pass it as a reference, and man I tried several ways...

I'll try this suggestion when I get home. Thx

Share this post


Link to post
Share on other sites

This topic is 4689 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this