final class in c++

2019-02-06 06:26发布

class Temp
{
private:
    ~Temp() {}
    friend class Final;
};

class Final : virtual public Temp
{
public:
     void fun()
     {
         cout<<"In base";
     }
};

class Derived : public Final
{
};

void main()
{
    Derived obj;
    obj.fun();
}

The above code tries to achieve non-inheritable class (final). But using above code the object of derived can still be created, why?

The desired functionality is achieved only if ctor made private, my question is why it is not achievable in case of dtor private?

7条回答
smile是对你的礼貌
2楼-- · 2019-02-06 07:10

And of course the proper way to do it today is to use the final keyword. For example:

class Foo final {
public:
  Foo() {}
  ~Foo() {}

  void bar() {
     // ...
  }
};
查看更多
登录 后发表回答