13
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?

dreamlax
  • 93,976
  • 29
  • 161
  • 209
Learner
  • 597
  • 1
  • 5
  • 17
  • 2
    Looks like defect with Visual studio. – Learner Sep 02 '09 at 09:17
  • 2
    this post: http://cpptalk.wordpress.com/2009/09/01/final-frozen-classes-in-cpp/ explains and shows how to create a final (frozen) class in c++. You are more than welcome to have a look. – rmn Sep 12 '09 at 12:11

7 Answers7

32

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.

Jeff Walden
  • 7,008
  • 2
  • 38
  • 55
11

Well, for this program (pleasse provide correct, compilable examples)

#include <iostream>

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

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

class Derived : public Final {};

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

Comeau Online says

Comeau C/C++ 4.3.10.1 (Oct  6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing.  All rights reserved.
MODE:strict errors C++ C++0x_extensions

"ComeauTest.c", line 16: error: "Temp::~Temp()" (declared at line 6) is inaccessible
  class Derived : public Final {
                         ^
          detected during implicit generation of "Derived::Derived()" at line
                    21

"ComeauTest.c", line 16: error: "Temp::~Temp()" (declared at line 6) is inaccessible
  class Derived : public Final {
        ^
          detected during implicit generation of "Derived::~Derived()" at line
                    21

2 errors detected in the compilation of "ComeauTest.c".

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.)

sbi
  • 219,715
  • 46
  • 258
  • 445
  • Yes i used VC.. Thanks for pointer, I think i will try will gcc also. – Learner Sep 02 '09 at 08:42
  • 1
    +1 gcc also complains about that code. How can VS destroy Derived not having access to Temp, what is required having virtual inheritance in Final???? – Fernando N. Sep 02 '09 at 09:49
  • 3
    @frieto: Access protection is a pure compiler front end feature. There's no magic to it. Once the front end accepts the code, the back end simply injects a call to the function that is the dtor. – sbi Sep 02 '09 at 10:37
  • @sbi: Ohh yes, but its a basic rule. Is like they are not taking into account the virtual inheritance to check access permission. – Fernando N. Sep 02 '09 at 15:13
  • 2
    @frieto: Well, in fact I _am_ saying they are not taking into account the virtual inheritance to check dtor access permission. (They do for the ctor, though.) And the matter is complicated enough that most of us more _guessed_ than _knew_ whether VC is right or wrong. – sbi Sep 02 '09 at 16:57
  • @sbi: Derived destructor calls Temp one which is private. Why guessing? – Fernando N. Sep 02 '09 at 18:02
  • 1
    @fnieto: I said it right, so why ask me? `:)` (Sorry for misspelling your nick, BTW. That's a hard to read font, once you're as old as I am.) – sbi Sep 02 '09 at 22:09
  • @sbi: It was a rhetorical question ;) – Fernando N. Sep 03 '09 at 06:20
  • @fnieto: So take my answer as rhetorical. `:^>` – sbi Sep 03 '09 at 09:41
6

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() {
     // ...
  }
};
5

The C++ FAQ describes different ways to achieve this – but from your question I guess you’ve already read them. ;-)

(Also, main must always return int, never void.)

eldruin
  • 332
  • 3
  • 16
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 2
    Since `Derived` has to call the ctor of `Temp`, doesn't it have to call its dtor, too? – sbi Sep 02 '09 at 08:40
  • 2
    @sbi: I *thought* that different rules applied to the destructor but your Comeau output makes a case for the opposite. I’ll let my answer stand anyway since it references the FAQ and mentions that `void` isn’t valid on `main`. Otherwise, your answer seems to nail it. It should be interesting to see how the code compiled by VS behaves, in particular if the destructor of a virtual base class gets called multiple times in multiple inheritance hierarchies. – Konrad Rudolph Sep 02 '09 at 09:05
  • @Konrad: I also only guessed, but como confirmed my guess, not yours. `:)` VC accepts my code (I should have written this in my answer. Sorry.) I suppose that's a bug in VC. – sbi Sep 02 '09 at 10:32
  • @Konrad: I tested that and VC++ do it ok, virtual inheritance works ok. The problem is only in access permission. -1 for saying "Derived doesn’t need to know Temp’s destructor". Why then should he use virtual inheritance? – Fernando N. Sep 03 '09 at 09:19
5

Curiously recurring template pattern. Use private inheritence.

template< typename T > class Final
{
protected:
    Final() {}
    Final( Final const& ) {}
};

class X : private virtual Final<X>
{
  // whatever I want to do
};

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).

CashCow
  • 30,981
  • 5
  • 61
  • 92
0

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.

David Allan Finch
  • 1,414
  • 8
  • 20
0

I have modified the original code posted and verified this code in g++:

class Temp
{
private:
    Temp() {
        cout << "In Temp Class ctor" << endl;
    }
    ~Temp() {}
    friend class Final;
};

class Final : virtual public Temp
{
public:

    void fun()
     {
         cout<<"In base";
     }
};

class Derived : public Final
{
};

int main()
{
    Derived obj;
    obj.fun();

    return 0;
}

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,

hims
  • 325
  • 3
  • 10