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?
The C++ FAQ describes different ways to achieve this – but from your question I guess you’ve already read them. ;-)
(Also,
main
must always returnint
, nevervoid
.)Curiously recurring template pattern. Use private inheritence.
and you should find it impossible to derive anything from X because the virtual inheritence means that the most-derived class must construct the base class but it won't have any access to it.
(I haven't tested this code).
Well, for this program (pleasse provide correct, compilable examples)
Comeau Online says
Since, when in doubt, I always trust como (I have only ever found one error in it, but many in other compilers), I suppose VC9 (which accepts the code) is in error. (From that
void main()
I suppose you use VC, too.)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: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.
The derived class does not call the private destructor of the base class, hence it does not need visibility.
Make your constructors private and only provide a static generator function.
I have modified the original code posted and verified this code in g++:
Result: $g++ one.cpp -o one -lm -pthread -lgmpxx -kgmp -lreadline 2>&1
one.cpp: In constructor 'Derived::Derived()': one.cpp:8:9: error: 'Temp::Temp()' is private Temp() {
one.cpp:25:11: error: within this context class Derived: public Final
one.cpp:11:9: error: 'Temp::~Temp()' is private ~Temp() {}
one.cpp:25:11: error: within this context class Derived : public Final
one.cpp:11:9: error: 'Temp::~Temp()' is private ~Temp() {}
Note: It's a best practice not use void with 'main'.
Thanks,