Is it possible to forbid deriving from a class at compile time?

后端 未结 7 2097
甜味超标
甜味超标 2021-01-02 04:29

I have a value class according to the description in \"C++ Coding Standards\", Item 32. In short, that means it provides value semantics and does not have any virtual method

7条回答
  •  天涯浪人
    2021-01-02 04:44

    This solution doesn't work, but I leave it as an example of what not to do.


    I haven't used C++ for a while now, but as far as I remember, you get what you want by making destructor private.

    UPDATE:

    On Visual Studio 2005 you'll get either a warning or an error. Check up the following code:

    class A
    {
    public:
        A(){}
    private:
        ~A(){}
    };
    
    class B : A
    {
    };
    

    Now,

    B b;

    will produce an error "error C2248: 'A::~A' : cannot access private member declared in class 'A'"

    while

    B *b = new B();
    

    will produce warning "warning C4624: 'B' : destructor could not be generated because a base class destructor is inaccessible".

    It looks like a half-solutiom, BUT as orsogufo pointed, doing so makes class A unusable. Leaving answers

提交回复
热议问题