I need to take object as function parameter, but I dont know object name yet

How can I proceed?

Last edited on
It’s a dummy argument, so you can call it what you like within the function. There is is no need for the name within the function to be the same as in the calling routine.

All you need to know is the type.
If it's just a function declaration (not a definition) then you don't even need a name.

bool foo(int); // function named foo that takes an int as argument and returns a bool

It could still be a good idea to write a name for documentation purposes. It makes it easier to see what arguments you're supposed to pass and in what order.

 
int to_seconds(int, int); // What am I supposed to pass as arguments? 
 
int to_seconds(int hours, int minutes); // Clear as crystal!  


In the definition (implementation) you obviously need a name otherwise you will not be able to refer to it from inside the function.

1
2
3
4
int to_seconds(int hours, int minutes)
{
	return 60 * (minutes + 60 * hours);
}

When you have a parameter that is not used you would normally remove it, but in some rare cases you might want to keep it. In those situations you might want to remove the name (or at least comment it out) to avoid that the compiler gives you a warning about "unused parameter".

1
2
3
4
bool foo(int) // the parameter doesn't need a name because it's not used inside the function 
{
	return true; 
}

(Since C++17 [[maybe_unused]] is also an alternative)


Note that the parameter name doesn't need to be the same in the definition and other declarations, although using different names might be confusing.

1
2
3
4
// Having both of these in the code is allowed but it might
// be confusing to see different names for the same thing.
void draw_letter(char letter, int x, int y);
void draw_letter(char letter, int col, int row);


Also note that the name that we use for the parameter has nothing to do with the name of the variable that the user pass to the function. It doesn't even need to be a variable. It could be the result of some more complicated expression.
E.g. int seconds_since_midnight = to_seconds(current_time.get_hour(), current_time.get_minute());
Last edited on
Topic archived. No new replies allowed.