final class in c++

Learner picture Learner · Sep 2, 2009 · Viewed 18.2k times · Source
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?

Answer

Jeff Walden picture Jeff Walden · Nov 20, 2011

Note that non-inheritable classes exist in C++11 using the final keyword, specified before the : base1, base2, ..., baseN inheritance list or before the opening { if the class inherits from nothing:

class Final final { };
class Derived : public Final { }; // ERROR

With a little macro magic and some compiler-detection effort this can be abstracted away to work, or at worst do nothing, on all compilers.