Adam Adam - 1 year ago 46
C++ Question

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 {
bool someGuaranteedResult() { return true; }

class Child : public Base {
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.

Answer Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download