I’m playing with the default arguments for my Settings class in my project, so that I have a bit fewer methods declared.
For instance, I have these methods declared:
class Settings
{
// [..]
int getCurrentUserID(); // returns current user id
// you specify the user id
int setSetting( int value, int user_id );
// no user specified, use the current one, overloads the previous when called
// with only 1 argument
int setSetting( int value );
}
What I’d like to have is this simplified version:
class Settings
{
// [..]
int getCurrentUserID(); // returns current user id
// automatically selects the current user if no ID is provided
int setSetting( int value, int user_id = getCurrentUserID() );
}
But I get this error at compilation:
cannot call member function ‘int Settings::getCurrentUserID()’ without object
How could I tell the compiler to use the current instance (which is available through the this) of the Setting object to get the default value?
Is this authorized, by the way?
The method
getCurrentUserID()is not static, so you can only call it through an object. One option is to create 2 methods, like the ones bellow, this and call the one you need:Another option: assuming the ID is always positive, you can give a default negative ID on the method and verify inside the method if the method was called with an ID or not. Something like this: