Reputation: 537
I'm implementing a static polymorphism:
template<typename T>
class Base {
public:
void method() {
// do something
impl();
// do something else
}
void impl() { // intended to be private
static_cast<T*>(this)->impl();
}
};
class Derived : public Base<Derived> {
public:
void impl() { // intended to be private
}
};
This code is a static implementation of a dynamic polymorphic classes where void impl()
was pure virtual. So the base class was abstract.
Now these classes implement static polymorphism and therefore don't have pure virtual functions.
Is it possible to make Base class abstract, so that objects of this class can't be created?
Upvotes: 0
Views: 448
Reputation: 61970
You can use a protected destructor and constructors:
template<typename T>
class Base {
public:
void method() {
// do something
impl();
// do something else
}
void impl() { // intended to be private
static_cast<T*>(this)->impl();
}
protected:
Base() = default;
~Base() = default;
// If you don't want to implement proper copying/moving:
// Base(const Base&) = delete;
// Base(Base&&) = delete;
// Base& operator=(const Base&) = delete;
// Base& operator=(Base&&) = delete;
};
This will even disallow a derived class's member functions to create base class objects, as well as trying to delete a pointer whose static type is Base<T>
.
Upvotes: 2