Jump to content
  • Advertisement
Sign in to follow this  
Headkaze

[C++] TryGetObject()

This topic is 3291 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 use the TryGetObject() type of method all the time in C# but I can't seem to get it working in C++. What TryGet usually does it take a pointer to an object and return true or false. Here is an example in C++
bool CMyClass::TryGetObject(CClass* pClass)
{
	if(...)
	{
		pClass = m_object->GetObject(); // returns a pointer to CClass
		return true;
	}
	
	return false;
}
I don't know why but when I call it like so, even though I know pClass is assigned a correct pointer it is not being passed out of the function.
CClass* pClass = NULL;

if(TryGetObject(pClass))
{
	// It is returning true yet the pClass value is NULL
}

Share this post


Link to post
Share on other sites
Advertisement
You should pass argument as reference (as you do in in C# with ref keyword):

bool CMyClass::TryGetObject(CClass*& pClass)


rest of code stays the same.

Share this post


Link to post
Share on other sites
You have to remember that even if you are passing a pointer to an object, the pointer itself is passed by value. If you want to modify the pointer in the calling function, the parameter needs to be a pointer to a pointer or a reference to a pointer.

Share this post


Link to post
Share on other sites
In my opinion, passing your argument as a pointer-to-pointer (CClass**) makes the calling code more readable. When you pass the pointer by reference, it may not be obvious to the caller that the passed pointer (pClass) will be modified by TryGetObject(). It's all a matter of personal taste though.

If you decide to pass by pointer-to-pointer, TryGetObject() would look as follows:
bool CMyClass::TryGetObject(CClass** ppClass)
{
if(...)
{
*ppClass = m_object->GetObject(); // ppClass now points to a pointer to the object
return true;
}

return false;
}



And the calling code...
CClass *ptr = NULL;
if(something->TryGetObject(&ptr))
{
// yay!
}
else
{
// doh!
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!