Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ abstract class destructor [closed]

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?

like image 324
user3758182 Avatar asked Jun 19 '14 21:06

user3758182


2 Answers

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;
}
    
    
like image 153
aalimian Avatar answered Sep 20 '22 04:09

aalimian


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).

like image 33
Oleg Avatar answered Sep 23 '22 04:09

Oleg