Sign in to follow this  
Headkaze

[C++] TryGetObject()

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
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

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