I have some classes layed out like this
class A { public virtual void Render() { } } class B : A { public override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } protected virtual void SpecialRender() { } } class C : B { protected override void SpecialRender() { // Do some cool stuff } }
Is it possible to prevent the C class from overriding the Render method, without breaking the following code?
A obj = new C(); obj.Render(); // calls B.Render -> c.SpecialRender
Can you allow class to be inherited, but prevent the method from being over-ridden? Yes, just leave the class public and make the method sealed.
No. Constructors in Java cannot be overridden because they are not inherited.
In C++, there's no way to forbid it, it's just that by definition of "override", only virtual functions can be "overridden".
When the method is declared as virtual in a base class, and the same definition exists in a derived class, there is no need for override, but a different definition will only work if the method is overridden in the derived class. Two important rules: By default, methods are non-virtual, and they cannot be overridden.
You can seal individual methods to prevent them from being overridable:
public sealed override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup }
Yes, you can use the sealed keyword in the B class's implementation of Render:
class B : A { public sealed override void Render() { // Prepare the object for rendering SpecialRender(); // Do some cleanup } protected virtual void SpecialRender() { } }
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