Is anyone aware of a language feature or technique in C++ to prevent a child class from over riding a particular method in the parent class?
class Base { public: bool someGuaranteedResult() { return true; } }; class Child : public Base { public: bool someGuaranteedResult() { return false; /* Haha I broke things! */ } };
Even though it's not virtual, this is still allowed (at least in the Metrowerks compiler I'm using), all you get is a compile time warning about hiding non-virtual inherited function X.
You can prevent a class from being subclassed by using the final keyword in the class's declaration. Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method. An abstract class can only be subclassed; it cannot be instantiated.
Private, Static and Final Methods - Can't Overridden in Java If you are familiar with private and static modifier in Java, then you may be knowing that private method is not accessible in subclass, which means they can not be overridden as well, because overriding happens at child class.
When you can use the final
specifier for virtual methods (introduced with C++11), you can do it. Let me quote my favorite doc site:
When used in a virtual function declaration, final specifies that the function may not be overridden by derived classes.
Adapted to your example that'd be like:
class Base { public: virtual bool someGuaranteedResult() final { return true; } }; class Child : public Base { public: bool someGuaranteedResult() { return false; /* Haha I broke things! */ } };
When compiled:
$ g++ test.cc -std=c++11 test.cc:8:10: error: virtual function ‘virtual bool Child::someGuaranteedResult()’ test.cc:3:18: error: overriding final function ‘virtual bool Base::someGuaranteedResult()’
When you are working with a Microsoft compiler, also have a look at the sealed
keyword.
A couple of ideas:
Other than that, I'm not aware of a language feature that will lock away your function in such a way which prevents it from being overloaded and still able to be invoked through a pointer/reference to the child class.
Good luck!
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