Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent class inheritance in C++

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

like image 902
ring0 Avatar asked Feb 02 '10 12:02

ring0


People also ask

How can you prevent inheritance from a class?

You can prevent a class from being subclassed by using the final keyword in the class's declaration. Similarly, you can prevent a method from being overridden by subclasses by declaring it as a final method.

How do I restrict an inheritance from a class in C#?

In C# you use the sealed keyword in order to prevent a class from being inherited. In VB.NET you use the NotInheritable keyword. In Java you use the keyword final .


1 Answers

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.

like image 188
Peter N Lewis Avatar answered Sep 20 '22 22:09

Peter N Lewis