Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prevent a method from being overridden in subclasses?

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.

like image 712
Adam Avatar asked Aug 20 '08 06:08

Adam


People also ask

How can you prevent overriding from a subclass?

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.

Which keyword modifier prevents a method from being overridden in a subclass?

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.


2 Answers

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.

like image 80
moooeeeep Avatar answered Sep 30 '22 11:09

moooeeeep


A couple of ideas:

  1. Make your function private.
  2. Do not make your function virtual. This doesn't actually prevent the function from being shadowed by another definition though.

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!

like image 43
OJ. Avatar answered Sep 30 '22 11:09

OJ.