Gegham Chinaryan
Gegham Chinaryan

Reputation: 1

How to implement `final` semantics pre C++11?

C++11 introduced the final specifier, which allows a base class to prevent derivation or overriding of virtual functions in derived classes.

How can I enforce similar constraints on class inheritance and function overriding pre C++11?

Upvotes: 0

Views: 162

Answers (2)

alagner
alagner

Reputation: 4062

Making the class behave somewhat like "final" can be achieved using virtual inheritance and class friendship.

Personally I would not recommend using it in this manner, but it's certainly possible.

class seal
{
    friend class impl1;
    friend class impl2;
    seal() {} // note it's private!
};

struct interface
{
    virtual ~interface() {}
};

struct impl1 : interface, virtual seal
{};

struct impl2 : interface, virtual seal
{};


struct impl3 : impl2{}; // declaration works...

int main()
{
    impl1 i1;
    impl2 i2;
    impl3 i3; // ...but fails to compile here
}

https://godbolt.org/z/MjKhbaTo8

Upvotes: -2

selbie
selbie

Reputation: 104569

Best I can suggest is making the constructor private and enforcing a factory function for instantiation:

class Foo
{
public:
    static Foo* makeInstance(int initialX)
    {
        return new Foo(initialX);
    }


private:
    Foo(int initialX) :x(initialX) {}
    int x;
    int setX(int value) { x = value; }
    int getX() { return x; }
};

That should prevent inheritance. But it does require your callers to explicitly instantiate the object via the static makeInstance function or similar. And then explicitly delete it.

You can also have it return the object copy instead of by pointer.

static Foo makeInstance(int initialX)
{
    return Foo(initialX);
}

Upvotes: 0

Related Questions