Returning an Object pointer through a function

Started by
2 comments, last by Rad94 16 years, 1 month ago
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.
Advertisement
3 options:

void ChooseName(Character** theCharacter);//usageChooseName( &theCharacter );


void ChooseName(Character*& theCharacter);//usageChooseName( theCharacter );


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


#3 to me is the cleanest.

-me
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){};
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!

This topic is closed to new replies.

Advertisement