Подтвердить что ты не робот

Как запретить производный класс С++ выводить из базы, но разрешить из другого производного класса

Учитывая этот сценарий:

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

Ответ 1

Создайте конструкторы GrandParent private и Parent другу.

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

Кроме того, вы можете обменивать полиморфное разрушение GrandParents, делая частный деструктор:

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

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

Ответ 2

Еще один способ решить эту проблему - использовать "магию шаблонов". Вы должны добавить этот код после объявления класса Child:

 #include <type_traits>

 class Child : public Parent
 {
 };

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

Если вы попробуете изменить родительский класс на GrandParent, компилятор даст вам ошибку