Making a derived member function impossible to override?

Started by
14 comments, last by smr 15 years, 5 months ago
Quote:Original post by Antheus
My solution:
// This class is not intended to be derived...// This function should not be overriden


I used to think that too, until one day it came back to bite us quite hard ;) Admittedly we find the MSVC override keyword more useful than sealed....
Advertisement
Quote:People can override, but cannot replicate required behavior, causing the class to break.


I don't believe you ;)

struct A {  void bar() { internal_bar(); }private:  void internal_bar() {    x += 1;  }  int x;};struct B : public A {  void bar() { std::cout << "moo"; }};


Which is the same problem that bagder82 is trying to solve....
Why do you care so much about this? What's going to break if someone overrides the function in a derived class? Since it's not virtual, they're not going to be using it polymorphically, so it won't affect code that doesn't use that specific class; and presumably the author of that class has a reason; and if it's wrong, on his head be it.
@Zahlman

"Since it's not virtual, they're not going to be using it polymorphically"

In my example version I don't use the class polymorphically but there is definitely no reason why someone couldn't do this by accident on a class that has some of it's functions as virtual. This is what happened in the case I have.

Thanks anyway for the advice from everyone. We will probably go down the route of, "OVERRIDE THIS AT YOUR OWN PERIL" ;)
Quote:Original post by ToohrVyk
Don't make it virtual. If it absolutely has to be virtual, make it private and have a public function call it.

This is one of the reasons why virtual functions should never be public, only protected: you can make a virtual function private and therefore prevent any overrides.


You can override a virtual function even if it's private.

#include <iostream>class B{    public:        virtual ~B() { }        void call() { vcall(); }    private:        virtual void vcall() { std::cout << "B\n"; }};class D : public B{    private:        virtual void vcall() { std::cout << "D\n"; }};int main(){    D d;    d.call();    return 0;}


Virtual functions shouldn't be public because in my mind at least, "virtual" means "(customisable) implementation detail". Derived classes should be allowed to change the implementation (that's the whole point), but clients shouldn't be able to access it directly.
Quote:Original post by badger82
Hi All,

Does anyone have any idea on how to make a derived classes member function impossible to override? For example:

*** Source Snippet Removed ***

Thanks :)


Solution:
class A{    // Do NOT override this method.    void Foo(){};};


Then focus on important things.

This topic is closed to new replies.

Advertisement