Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ fix unused parameter warning with polymorphism

I get some compiler warnings for my program concerning unused variables, and I would like to know what is an appropriate way to fix this.

I have a function that gets inherited by the base class, and in the implementation of the function for the parent I don't use all parameters that are needed for the child; of course this leads to warnings, and as I am not an experienced programmer I am not sure what is the best way to fix those warnings.

So an minimal example would be:

In the header:

    class car{
     public:
       virtual void init(int color, int size)
     private:
       int size;
    }
    class sportscar : public car{
     public:
       virtual void init(int color, int size)
     private:
       int color;
       int size;
    }

In the source file:

    void car::init(int color, int size){
      this->size = size;
    }
    void sportscar::init(int color, int size){
      this->color = color;
      this->size = size;
    }
like image 700
user3047299 Avatar asked Dec 26 '22 17:12

user3047299


2 Answers

All you need to do is to not name them in the implementation:

void car::init(int /* color */, int size){
    this->size = size;
}
like image 197
quamrana Avatar answered Dec 28 '22 05:12

quamrana


You can omit the name of the function parameter.

void car::init(int, int size) {
  this->size = size;
}

This is sometimes not desirable because some tools use the signature to extract documentation and you define the function inline. Then you can use a cast.

struct car {
  void init(int color, int size) {
    (void)color; // prevent warning
    this->size = size;
  }
};

At the same time, please remember that C++ classes often don't need init functions because that's what constructors are for.

like image 45
pmr Avatar answered Dec 28 '22 06:12

pmr