azy.development
azy.development

Reputation: 23

NVI doesn't prevent name hiding; why not use virtual final instead?

Consider the following:

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;

class Foo {
public:
    // NVI
    bool method() {
        cout << "Foo::method" << endl;
        return method_impl();
    }

    // Why not do this instead?
    //virtual bool method() final {
    //    cout << "Foo::method" << endl;
    //    return method_impl();
    //}

private:
    virtual bool method_impl() = 0;
};

class Bar : public Foo {
public:
    // What stops someone from doing this hiding the Foo::method identifier?
    // Uncomment the below and see how the console output is instead Bar::method and then method_impl

    //bool method() {
    //    cout << "Bar::method" << endl;
    //    return method_impl();
    //}

private:
    virtual bool method_impl() override {
        return true;
    }
};


int _tmain(int argc, _TCHAR* argv[]) {
    Bar bar = Bar();

    cout << bar.method() << endl;

    return 0;
}

As you can see above, the Foo class is trying to follow the NVI pattern with the Foo::method() member function.

What prevents a child class, in this case Bar, from hiding the Foo::method() with Bar::method()? I tried it and I guess nothing. If you uncomment Bar::method(), the console application does indeed go down the Bar implementation of method() which makes total sense.

Which begs the question, why not use virtual final to disallow name hiding of that method in a child class? Example provided in the Foo class.

Thanks

Upvotes: 1

Views: 84

Answers (0)

Related Questions