I made my own class in C . I want that the class constructor can work with a default value of an optional argument, but the compiler should warn me that I didn't specify the optional argument. Is there a way to do this? I'm using g , so it's okay if the solution only works in gcc.
I think __attribute__
can do what I want, but I couldn't find how.
I want to do this:
class somestringclass{
private:
/* ... */
public:
somestringclass(char *x, int length = -1) {
if (length==-1)
{
//calculate length by finding '\0' in x,
//but I want to be warned to avoid potential memory issue by getting char array without '\0'.
}
/* some constructing here.. */
}
/* some other features here.. */
};
CodePudding user response:
Based on the current class definition and your expectations for the constructor I suggest that you split it into two different constructors - one for each use-case. The first constructor takes only a const char*
as the argument and the length of the string is determined by searching for a null terminator. The second constructor is similar to the one you have now except the length parameter is not defaulted (i.e. optional). When doing so I also suggest making the length
parameter an unsigned type (i.e. size_t
) since there can never be a string with a negative length (this applies to anything with a length or taking an index value). This way you can optionally check for a length of 0 and either throw an exception or assume that it is an empty string.
class somestringclass
{
private:
/* ... */
public:
somestringclass(const char *x)
{
// Calculate length of string by searching for null terminator
}
somestringclass(const char *x, size_t length)
{
// Check length for 0 if that is not supported or assume empty
}
};
A good use case for having the second constructor that takes a length is the ability to create a string from either a character buffer that may not be null terminated or from only a portion of another string (a substring). This provides a greater amount of usability in your string class. For reference I suggest you look at the constructors of std::string
and think about the different ways you might use them to create a string.
This should give you a greater sense of reliability and clarity in the usage of your string type.
Note that I've changed the char*
pointer argument to const
to allow passing string literals to the constructor.