I have used the following C++ rule of thumb for a long time:
If a class overrides a function in its base class, the function should be declared
virtual
in the base.
I think I have come across an exception from this rule. To judge whether this is justified, or points at a flaw in my design, I am asking this question. I would like to get examples or better rules.
Edit: I tried describing my use case here, and I have understood that I don't really need inheritance!
I wanted to ask a general question though. Thanks for the answers!
You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
C++ has access control, but not visibility control. This means that private functions are visible but not accessible. A private virtual function can be overridden by derived classes, but can only be called from within the base class.
You can call a virtual function in a constructor, but be careful. It may not do what you expect. In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn't yet happened. Objects are constructed from the base up, “base before derived”.
Virtual functions are slow when you have a cache miss looking them up. As we'll see through benchmarks, they can be very slow. They can also be very fast when used carefully — to the point where it's impossible to measure the overhead.
You can not override a non-virtual function. Only thing you can do is to hide the base class implementation. But this doesn't provide you the polymorphic behavior that virtual function provide.
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