Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing a reference to a member function

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Ok, the thing is... I got the whole 'passing a reference' thing down. My problem is the whole gist of getting the correct data types in strcpy... This is essentially what my feeble mind is trying to do:
--------------------------------------------------------
void <classname>::setname(char &n){
strcpy(name,n); }

// from my main()
<classname> ob1;
char n[12];
n = &quot;Jimmy&quot;; //Just an example, im really going by user input
ob1.setname(n);
----------------------------------------------------------
I've also tried passing pointers... can anyone point out my flaw or tell me if this is even possible? Im so new at this!!
 
strings are a bit different in the way you set them.

When declaring the string you can do

char n[] = &quot;Jimmy&quot;;

but char n[12];
n = &quot;Jimmy&quot; will not work as expected...

You should do

strcpy(n,&quot;Jimmy&quot;);


As for the function it should look like:

void <classname>::setname(char* n){
strcpy(name,n); }

By default, pointers are passed by reference.

I hope this clarified it a bit.

Matt

 
Ok, Matt, thanks! That actually helped clear things up a bit.. fixed a bunch of errors but now i got 3 left! ;)
I think its in how I am passing these strings to the member function. My strings are all randomly based on user input with a maximum of 12 chars. I am then setting my char variable after they make their input.

I am setting and sending it somewhat like this:
cin >> a;
if (a=1)
name = &quot;Jimmy&quot;;
//etc..
else
name = &quot;Unknown&quot;;

ob1.setname(&name);

Am I way out in left field over here?? ;)
 
Only 1 mistake there - assuming name is a char* variable, you should call ob1.setname(name). Of course, to make this really C++, you could ditch the char* (C-strings) and use the STL string class...it's much easier to deal with IMO.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top