Thursday, May 30, 2013

unused parameters in function

When you have an interface with an abstract base class Base and several classes that have derived from it. For a while this setup works out well, but at some point you have another class that inherits from Base and also has its definitions for the virtual functions. For one of the virtual functions you do not need all of the function arguments. This will cause a compiler warning in case you compile with gcc
and set the flags "-Wall -Wextra".

class Base {
public:
  virtual bool some_func(bool param) = 0;
};

class DerivedClass1 : public Base {
public:
  virtual bool some_func(bool param) {return param;}
};

class DerivedClass2 : public Base {
public:
  virtual bool some_func(bool param) {return true;}
};


It is obvious that you want to get rid of all compiler warnings. One possible solution is to make a void cast on param (taken from stackoverflow):

class DerivedClass2 : public Base {
public:
  virtual bool some_func(bool param) {(void)param; return true;}
};


Another solution that is - in my opinion - more elegant, is to just specifiy the parameter type without giving a variable name for the functions that do not use that parameter (also from stackoverflow):

class DerivedClass2 : public Base {
public:
  virtual bool some_func(bool /*param*/) {return true;}
};

No comments:

Post a Comment