pacorrop
pacorrop

Reputation: 577

How to forbid C++ derived class to derive from base, but allow from another derived class

Given this scenario:

class GrandParent {};
class Parent : public GrandParent {};
class Child : public Parent {}; /// Ok
class Child : public GrandParent {}; /// Is it possible to force a compilation error? 

Upvotes: 19

Views: 1090

Answers (2)

user2249683
user2249683

Reputation:

Make the GrandParent constructors private and the Parent a friend.

class GrandParent
{
   friend class Parent;
   private:
   GrandParent() {}
   // ...
};

Alternatively, you may trade off polymorphic destruction of GrandParents by making the destructor private:

class GrandParent
{
   friend class Parent;
   private:
   virtual ~GrandParent() {}
};

// Invalid Destruction:
GrandParent* p = new Parent;
...
delete p;

Upvotes: 39

Alex Aparin
Alex Aparin

Reputation: 4522

Another way to solve this problem is to use "template magic". You should add this code after Child class declaration:

 #include <type_traits>

 class Child : public Parent
 {
 };

 static_assert(std::is_base_of<Parent, Child>::value, "Child must derive Parent");

If you try change Parent class to GrandParent, compiler gives you error

Upvotes: 0

Related Questions