I have a base class with an optional virtual function
class Base { virtual void OnlyImplementThisSometimes(int x) {} };
When I compile this I get a warning about the unused param x. Is there some other way I should have implemented the virtual function? I have re-written it like this:
class Base { virtual void OnlyImplementThisSometimes(int x) { x = 0; } };
I also have the problem that if I’m not careful, the subclass I make can implement the wrong function and then I don’t notice because of overloading: e.g.
class Derived : public Base { void OnlyImplementThisSometimes(int x, int y) { // some code } }; Derived d; Base *b = dynamic_cast<Base *>(&d); b->OnlyImplementThisSometimes(x); // calls the method in the base class
The base class method was called because I implemented the derived function with an ‘int y’ param but there is no warning about this. Are these just common pitfalls in C++ or have I misunderstood virtual functions?
Ignoring the design issues you can get around the compiler warning about an unused variable by omitting the variable name, for example:
Mistakenly implementing the wrong method signature when trying to override the virtual function is just something you need to be careful about in C++. Languages like C# get around this with the ‘override’ keyword.