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?
Yes, C++ virtual functions can have default parameters.
Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument.
15 Answers. Show activity on this post. Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. All C++ implementations should call the version of the function defined at the level of the hierarchy in the current constructor and no further.
A pure virtual function makes it so the base class can not be instantiated, and the derived classes are forced to define these functions before they can be instantiated. This helps ensure the derived classes do not forget to redefine functions that the base class was expecting them to.
Ignoring the design issues you can get around the compiler warning about an unused variable by omitting the variable name, for example:
virtual void OnlyImplementThisSometimes(int ) { }
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.
We define a macro _unused
as:
#define _unused(x) ((void)x)
Then define the function as:
virtual void OnlyImplementThisSometimes(int x) { _unused( x );}
This not only keeps the compiler from complaining, but makes it obvious to anyone maintaining the code that you haven't forgotten about x -- you are intentionally ignoring it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With