73

Recently one of my friend asked me how to prevent class inheritance in C++. He wanted the compilation to fail.

I was thinking about it and found 3 answers. Not sure which is the best one.

1) Private Constructor(s)

class CBase
{

public:

 static CBase* CreateInstance() 
 { 
  CBase* b1 = new CBase();
  return b1;
 }

private:

 CBase() { }
 CBase(CBase3) { }
 CBase& operator=(CBase&) { }


};

2) Using CSealed base class, private ctor & virtual inheritance

class CSealed
{

private:

 CSealed() {
 }

 friend class CBase;
};


class CBase : virtual CSealed
{

public:

 CBase() {
 }

};

3) Using a CSealed base class, protected ctor & virtual inheritance

class CSealed
{

protected:

 CSealed() {
 }

};

class CBase : virtual CSealed
{

public:

 CBase() {
 }

};

All the above methods make sure that CBase class cannot be inherited further. My Question is:

  1. Which is the best method ? Any other methods available ?

  2. Method 2 & 3 will not work unless the CSealed class is inherited virutally. Why is that ? Does it have anything to do with vdisp ptr ??

PS:

The above program was compiled in MS C++ compiler (Visual Studio). reference : http://www.codeguru.com/forum/archive/index.php/t-321146.html

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
ring0
  • 791
  • 2
  • 7
  • 5

8 Answers8

97

As of C++11, you can add the final keyword to your class, eg

class CBase final
{
...

The main reason I can see for wanting to do this (and the reason I came looking for this question) is to mark a class as non subclassable so you can safely use a non-virtual destructor and avoid a vtable altogether.

Peter N Lewis
  • 17,664
  • 2
  • 43
  • 56
  • 3
    There is another good reason and that's preventing derived classes to break the contract of the immutable classes. – Nemanja Boric Apr 12 '14 at 09:20
  • @Nemanja Boric that would apply to any subclass and any contract, not just mutability. Any subclass can potentially break any implied contracts of the class - that isn't really a good reason for disallowing all subclasses. For an immutable object, what if you want to add a derived value, for example FullName() from FirstName() and LastName() methods, or perhaps a specific hash function. – Peter N Lewis Apr 16 '14 at 08:24
  • @PeterNLewis - with proper design derived classes breaking the contract can be mitigated (at least at runtime.... ONLY protected members virtual. All calls to the virtual member have pre and post checks... therefore users have to call the non-virtual (contract enforcing) method which checks both pre-and post conditionas and can squarely "blame" the derived clas if the contract is broken. – David V. Corbin Sep 01 '22 at 10:36
  • @DavidV.Corbin actually, going back to immutability, no design could prevent an immutable class being made mutable via subclassing (with new mutable properties), which would change the class from a value class to a mutable class. None of which is really a problem - the purpose of subclassing is to change or extend behaviour, so a subclass does not necessarily have to follow the same contract as the superclass. – Peter N Lewis Nov 02 '22 at 08:30
  • @PeterNLewis - I disagree, and so would Barbara Liskov.... If I write code that takes a (potential) base class, then any theoretical future derived classes MUST operate in the exact same way. Taken strictly, this means that if base class can throw X or Y, then a derived class which could also throw Z would be a violation. – David V. Corbin Mar 27 '23 at 17:38
14

You can't prevent inheritance (before C++11's final keyword) - you can only prevent instantiation of inherited classes. In other words, there is no way of preventing:

class A { ... };

class B : public A { ... };

The best you can do is prevent objects of type B from being instantiated. That being the case, I suggest you take kts's advice and document the fact that A (or whatever) is not intended to be used for inheritance, give it a non-virtual destructor, and no other virtual functions, and leave it at that.

lorro
  • 10,687
  • 23
  • 36
8

You are going through contortions to prevent further subclassing. Why? Document the fact that the class isn't extensible and make the dtor non-virtual. In the spirit of c, if someone really wants to ignore the way you intended this to be used why stop them? (I never saw the point of final classes/methods in java either).

//Note: this class is not designed to be extended. (Hence the non-virtual dtor)
struct DontExtened
{
  DontExtened();
  /*NOT VIRTUAL*/
  ~DontExtened();
  ...
};
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
KitsuneYMG
  • 12,753
  • 4
  • 37
  • 58
  • 13
    I think the point in Java is that the JIT compiler can optimize calls to virtual methods if the class is final – Manuel Feb 02 '10 at 13:39
  • @Manuel. I understand the jvm may like it, but there should be a easy way to undo that w/o changing the source. `@ReallyOverride?` – KitsuneYMG Feb 02 '10 at 14:20
  • 1
    That's getting sidetracked a bit. In Java, the `final` keyword makes sense because all functions are virtual by default, and so there's a lot to gain by allowing the JIT compiler to perform these optimizations. In C++, there'd be nothing to gain from a similar mechanism to prevent subclassing, which is why the language doesn't supply a mecehanism for doing it. – jalf Feb 02 '10 at 15:54
  • 1
    Sanity ftw. Let people shoot themselves in the foot if they want to. – Ed S. Oct 27 '10 at 22:53
  • 16
    -1: Such contortions are for accidents. Also, this does not answer the OP's question (even if it *may* (it's not) be an X-Y problem). Your answer is equivalent to make everything public and document every logically private item as such. My rule is let the compiler help you not make mistakes when possible. – Thomas Eding Sep 04 '14 at 20:45
  • @ThomasEding Well, you can think that, but you're dead wrong. This is the idiomatic way in c++ 2011. My rule is to write code that can be expected to be well understood by the wider community of coders for a language. Also, if your compiler does not warn you about inheriting from a class with a non-virtual dtor, you need a new one. – KitsuneYMG Sep 05 '14 at 10:40
  • 6
    I thought C++11 had `final` for that very purpose. Thus I would expect that to be the idiomatic way to do so in C++11. Why use comments when you have a language feature to do exactly what the comments try (but fail) to enforce? – Thomas Eding Sep 05 '14 at 18:53
  • 4
    I agree with @ThomasEding the `final` identifier, is the better option. It allows the compiler to assist you, and documents very precisely that this class is not intended for inheritance. If you choose to take the path of comments, then you would have the programmer look up the source, and interpret the comment. Which can be multiple lines, perhaps even within a larger commenting block. By using `final` the IDE can help when at first attempting to inherit from the class. Besides using `final` the developer knows where to look, even if he/she is not used to the programming style used. – Tommy Andersen Apr 10 '15 at 13:16
  • 1
    This answer has other problems in addition, including deriving from a derived class with a virtual destructor; and legitimate non-virtual subclassing (take `std::unary_function` for instance). http://stackoverflow.com/questions/7403883/derived-class-with-non-virtual-destructor – Thomas Eding Apr 10 '15 at 19:23
  • 1
    -1. My compiler doesn't read documentation, and sometimes my colleagues don't either. Enterprise-quality software outsources constraints to the code. – Andrew Lazarus Oct 23 '15 at 21:49
  • The reason I'm using `final` on my struct is because I use it by value in a `std::vector`. If someone extends it and gets one in the `std::vector`, that's real bad. – lmat - Reinstate Monica Jan 13 '16 at 15:02
4

1) is a matter of taste. If I see it correctly, your more fancy 2nd and 3rd solutions move the error in certain circumstances from link time to compile time, which in general should be better.

2) Virtual inheritance is needed to force the responsibility to initialize the (virtual) base class to the most derived class from where the base class ctor is no longer reachable.

Whoever
  • 33
  • 1
  • 7
4

To answer your question, you can't inherit from CBase because in virtual inheritance a derived class would need to have direct access to the class from which it was inherited virtually. In this case, a class that would derive from CBase would need to have direct access to CSealed which it can't since the constructor is private.

Though I don't see the usefulness of it all (ie: stopping inheritance) you can generalize using templates (I don't think it compiles on all compilers but it does with MSVC)

template<class T>
class CSealed
{
    friend T;    // Don't do friend class T because it won't compile
    CSealed() {}
};

class CBase : private virtual CSealed<CBase>
{
};
Thomas Eding
  • 35,312
  • 13
  • 75
  • 106
Francis Boivin
  • 255
  • 1
  • 7
0

If you can, I'd go for the first option (private constructor). The reason is that pretty much any experienced C++ programmer will see that at a glance and be able to recognize that you are trying to prevent subclassing.

There might be other more tricky methods to prevent subclassing, but in this case the simpler the better.

T.E.D.
  • 44,016
  • 10
  • 73
  • 134
-1
class myclass;

    class my_lock {
        friend class myclass;
    private:
        my_lock() {}
        my_lock(const my_lock&) {}
    };

    class myclass : public virtual my_lock {
        // ...
    public:
        myclass();
        myclass(char*);
        // ...
    };

    myclass m;

    class Der : public myclass { };

    Der dd;  // error Der::dd() cannot access
            // my_lock::my_lock(): private  member

I found it here to give credit. I am posting here just other people can easily access http://www.devx.com/tips/Tip/38482

Vijay
  • 1
-1

To elaborate on Francis' answer: if class Bottom derives from class Middle, which virtually inherits from class Top, it is that most derived class (Bottom) that is responsible for constructing the virtually inherited base class (Top). Otherwise, in the multiple-inheritance/diamond-of-death scenario (where virtual inheritance is classically used), the compiler wouldn't know which of the two "middle" classes should construct the single base class. The Middle's constructor's call to the Top's constructor is therefore ignored when Middle is being constructed from Bottom:

class Top {
    public:
        Top() {}
}

class Middle: virtual public Top {
    public:
        Middle(): Top() {} // Top() is ignored if Middle constructed through Bottom()
}

class Bottom: public Middle {
    public:
        Bottom(): Middle(), Top() {}
}

So, in the the approach 2) or 3) in your question, Bottom() can't call Top() because it's inherited privately (by default, like in your code, but it's worth making it explicit) in Middle and thus is not visible in Bottom. (source)

Community
  • 1
  • 1
Błażej Czapp
  • 2,478
  • 2
  • 24
  • 18