1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

help with c++ parameter passing.

Discussion in 'Mac Programming' started by chris200x9, Sep 21, 2008.

  1. macrumors 6502a

    #1
    hi, I'm new-ish to c++ and I have a program:
    Code:
    #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.
     
  2. macrumors 6502

    #2
    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?
     
  3. macrumors 6502a

    #3
    In your constructor for Person, there's no real point in calling the setters since you have access to the Private variables there.
     
  4. macrumors newbie

    #4
    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.
     
  5. macrumors 6502a

    #5
    For the code as posted, there was no point. But for the paradigm you presented, yes, that is a better approach.
     

Share This Page