Is it good practice (and is it possible) to create an abstract class using only a pure virtual destructor in the parent class?
Here's a sample
class AbstractBase {
public:
AbstractBase () {}
virtual ~AbstractBase () = 0;
};
class Derived : public AbstractBase {
public:
Derived() {}
virtual ~Derived() {}
};
Otherwise how can I create an abstract class if the attributes and constructors of the derivatives class are all the same while the other method are totally different?
An interface in C++ SHOULD have a virtual destructor that is implemented and does nothing. All the other methods in the interface have to be defined abstract (e.g. adding = 0 in the declaration). This will ensure that you will not be able to create an instance of your interface class, but you can delete your object once you have assigned your interface pointer to the parent object. Sorry for bad wording, below is some code:
class ISampleInterface
{
public:
virtual ~ISampleInterface() { };
virtual void Method1() = 0;
virtual void Method2() = 0;
}
class SampleClass : public ISampleInterface
{
public:
SampleClass() { };
void Method1() { };
void Method2() { };
}
int main()
{
ISampleInterface *pObject = new SampleClass();
delete pObject;
return 0;
}
Having only a pure virtual destructor in the base class is rarely a good practice, but it is possible and, in certain cases, even desirable.
For instance, if you rely on RTTI to dispatch messages to a subclass object by attempting a dynamic_cast on the pointer to the base class, you may need no methods in the base class except the destructor. In this case, make the destructor public virtual.
Since you have no other virtual methods except the destructor, you have to make it pure in order to prevent the creation of the objects of the base class.
Here, it is crucial to provide the empty body to that destructor (even though it is "=0"!)
struct AbstractBase {
virtual ~AbstractBase() = 0;
}
AbstractBase::~AbstractBase() {
}
Having the body allows the creation of subclass objects (provided that the subclass defines the destructor and does not set it as pure).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With