PDA

View Full Version : help with c++ parameter passing.




chris200x9
Sep 21, 2008, 11:40 AM
hi, I'm new-ish to c++ and I have a program:

#include <iostream>
#include <string>
using namespace std;

class Person{
private:
string guysname;
int guysage;
public:
Person (string name, int age)
{
setGuysName(name);
setGuysAge(age);
}
void setGuysName(string name) {
guysname = name;
}
string getGuysName()
{
return guysname;
}
void setGuysAge(int age)
{
guysage = age;
}

int getGuysAge(string type)
{
if (type == "coolguy")
{
return guysage - 5;
}

if (type == "weirdo")
{
return guysage;
}
return 0;
}

void displayMessage()
{
cout <<"yo' name is: " << getGuysName() << " and you are " << getGuysAge(string type ) << endl;
}



};


int main()
{
Person a("bob", 30);





return 0;
}


and I'm having a dickens of a time trying to figure out why I am getting the error message "primary expression expected before type" in my display message function. I would very much appreciate any help, thank you.



kpua
Sep 21, 2008, 11:57 AM
When you pass parameters, you just pass the variables not the variable's type. So it's just "type" instead of "string type" in your displayMessage() method.

Also, "type" isn't declared in the scope of that message. Shouldn't have you have a setter/getter/instance variable for it too?

toddburch
Sep 21, 2008, 07:04 PM
In your constructor for Person, there's no real point in calling the setters since you have access to the Private variables there.

skinnybeans
Sep 21, 2008, 08:07 PM
In your constructor for Person, there's no real point in calling the setters since you have access to the Private variables there.

There is a point, doing checking on the variables. What if you wanted to check that the age was > 0 and you put this logic in the setAge() function. If you are going to set the age variable directly from the constructor, you ignore this check. Of course you could copy the validation code, but that is pretty sloppy way of doing it. If you are really that worried about the performance implications (you may be constructing lots of objects, but modifying them rarely) you can always make the set method inline.

toddburch
Sep 22, 2008, 07:30 PM
For the code as posted, there was no point. But for the paradigm you presented, yes, that is a better approach.