C ++ virtual function with arguments receiving warnings when not used

virtual void myFunc(int& a, int& b) {} 

I get warnings about unused variables, but I don't want to do anything with them in the base class. I want derived classes to implement them if they want, and do nothing if they do not implement them. What can I do to stop warnings other than putting a flag in the compiler?

+6
source share
6 answers

Just don't give them a name:

 virtual void myFunc( int&, int& ); 
+22
source

Since you do not want to use them, you can generate parameter names.

However, instead of completely deleting them, it is sometimes more useful to comment them as follows:

 virtual void myFunc(int& /* a */ , int& /* b */ ) { } 

Thus, you can still see what the purpose of this parameter is if you look at the commented out name. This is especially useful if you put the implementation in the header, as this will be the only place where parameter names are mentioned.

+9
source

You have several ways to disable this warning.

  • Remove them from the declaration / definition:

     virtual void myFunc(int& /* a */ , int& /* b */ ) {} 

    This solution can trigger some warnings with some tool like Doxygen ...

  • Use the trick to indicate that the argument is not used:

     template <typename T> void unusedArg(const T&) {} // Helper function. // In the class virtual void myFunc(int& a, int& b) { unusedArg(a); unusedArg(b); } 

    or in C ++ 11:

     template <typename ... Ts> void unusedArgs(const Ts...&) {} // Helper function. // In the class virtual void myFunc(int& a, int& b) { unusedArgs(a, b); } // C++11 
  • In C ++ 17, you can also use the [[maybe_unused]] attribute:

     // In the class virtual void myFunc([[maybe_unused]] int& a, [maybe_unused]] int& b) {} 
+6
source

Try defining a function without parameter names as

 virtual void myFunc(int& ,int& ) { } 

Also consider creating an abstract base class.

 virtual void myFunc(int& a,int& b ) = 0; 

if it just simplifies the interface.

+4
source

On some compilers, you can simply write the variable name as the "no-op" operator.

 virtual void myFunc(int& a, int& b) { a; // unused variable b; } 

However, to support other compilers and make it clear, you can use a macro or the unused_argument function to make it clear.

If this does not work with your compiler, I think doing sizeof(a); will work.

0
source

In Qt (5.x and higher, perhaps even earlier) you have access to Q_UNUSED located in qglobal.h . This macro casts to the void argument, and the result is not saved anywhere - and therefore no side effects other than using the variable in such a way that GCC deems acceptable.

0
source