Question

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;
    }
Was it helpful?

Solution

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

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

OTHER TIPS

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.

There no need to name function parameters: if you don't use a parameter, just leave its name off:

void car::init(int, int size) {
    this->size = size;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top