Reputation: 577
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
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
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