Sign in to follow this  
Rad94

Returning an Object pointer through a function

Recommended Posts

Hey guys I'm working on the Combat Simulator project in the CPP workshop and I'm stuck on how to return my character object pointer through functions.
	if (choice == 'a')
		{
			if (theCharacter == 0)
			{
			system("cls");
			ChooseName(&theCharacter);
			}

			else
			cout << "Character already created.";	
		}

void ChooseName(Character* theCharacter)
{
	string name;
	cout << "Enter the name you would like for your character.\n";
	cout << "Name: ";
	cin >> name;

	theCharacter = new Character(name);
	cout << "Your character, " << theCharacter->GetName() << ", has been created.\n";
	
}

This generates a compile error due to the address symbol(&). But if I take it off, theCharacter won't return its data properly.
//After ChooseName() is over
cout << "Your character is named " << theCharacter->GetName() << endl;
//Run-time error: Access violation reading location 

Help would be greatly appreciated.

Share this post


Link to post
Share on other sites
3 options:


void ChooseName(Character** theCharacter);

//usage

ChooseName( &theCharacter );




void ChooseName(Character*& theCharacter);

//usage

ChooseName( theCharacter );




Character* ChooseName()
{
//blah blah
return new Character(name);
}

//usage

theCharacter = ChooseName();



#3 to me is the cleanest.

-me

Share this post


Link to post
Share on other sites
Quote:
This generates a compile error due to the address symbol(&).


Character * ChooseName()
{
string name;
cout &lt;&lt; "Enter the name you would like for your character.\n";
cout &lt;&lt; "Name: ";
cin &gt;&gt; name;

Character * cptr = new Character(name);
cout &lt;&lt; "Your character, " &lt;&lt; cptr-&gt;GetName() &lt;&lt; ", has been created.\n";
return cptr;
}




if (theCharacter == NULL)
{
system("cls");
theCharacter = ChooseName();
}




Another alternative, but less intuitive would be:

void ChooseName( Character * &theCharacter)
{
...
theCharacter = new Character(name);
...
};

,,,
ChooseName(theCharacter);




This falls under passing by reference.

While somewhat obscured above, this may seem more recognizable:

typedef Character * CharacterPtr;

void ChooseName(CharacterPtr & character)
{
};

Share this post


Link to post
Share on other sites
Quote:
Original post by Palidine
3 options:

*** Source Snippet Removed ***

*** Source Snippet Removed ***

*** Source Snippet Removed ***

#3 to me is the cleanest.

-me


Thanks alot!

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