I made an own class in C++. I want that the class constructor can work with default value of optional argument, but the compiler warns me that I didn’t specify the optional argument. Is there a way? 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.. */
};
>Solution :
In C++, you can use the [[deprecated]] attribute to mark a function as deprecated and generate a warning whenever it is used. This attribute can be applied to a function or function overload, and can be used to indicate that the function should no longer be used.
For example, suppose you have a class MyClass with a constructor that takes an optional argument arg. You can mark the constructor as deprecated and generate a warning when it is called with the default value for arg like this:
class MyClass {
public:
[[deprecated("Please specify a non-default value for 'arg'")]]
MyClass(int arg = 0) {
// ...
}
};
Now, if someone calls the constructor with the default value for arg, they will receive a warning similar to this:
warning: 'MyClass::MyClass(int)' is deprecated: Please specify a non-default value for 'arg' [-Wdeprecated-declarations]
MyClass obj;
^
Note that this attribute is only supported in C++11 and later. If you are using an older version of C++, you may need to use a different approach.
Alternatively, you can define a separate overload of the constructor that takes no arguments, and mark that overload as deprecated. This will generate a warning whenever the no-argument constructor is called, while still allowing the optional argument constructor to be used without generating a warning.
class MyClass {
public:
MyClass(int arg) {
// ...
}
[[deprecated("Please specify a non-default value for 'arg'")]]
MyClass() {
// ...
}
};