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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help on defining constructors easily...

Status
Not open for further replies.

shadowsilver

Programmer
Nov 26, 2002
10
US

Does anyone know if there is a way to send arguments to a constructor and not have to use a local copy to transfer them to their rightful homes?

Like:

class Person {
int Hlth, Att, Def;
string Name;
Person(int InitHlth, int InitAtt, int InitDef, string InitName);
}
Is there another way to do it than this? It seems sorta redundant.

Person::person(int InitHlth, int InitAtt, int InitDef, string InitName) {
Hlth = InitHlth;
Att = InitAtt;
Def = InitDef;
Name = InitName;
}

Person Me(50, 10, 2, "Bob");

Can you do it with references or pointers? I haven't had any luck... I've tried like Person::person(int &Hlth, int &Def, etc) but I don't know how to make it work.
 
Nope, you have to use local parameters. You can use references and avoid making copies of your data, although that's pretty pointless for ints and such, and it still requires you to make a local reference parameter with a name, which you consider redundant.

It's not really redundant, though. Think in terms of a function that initializes a global variable. You need the local copy to refer to the value passed in as an argument. Without the local copy, the question "initialize it to what?" arises.

[tt]int x = 5;
[/tt]
You need both x (what gets initialized) and 5 (what it gets initialized to) for the statement to make sense.

Think about it from the function's perspective. It has a given value, and its instructions are to initialize a certain member variable to that value. The fact that the member variable and the variable containing the value have similar names doesn't make it redundant.
 
Thanks for the clarification, chipperMDW. I just wondered whether it was possible. It's not really any harder, but I just figured it would simplify my code if you could do that. I wasn't sure whether C++ came with a way to automate that kind of initializing, seeing as how I would think it would be used often. But like I would know :}
Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top