Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual destructor for boost:noncopyable classes?

I have a question about the following code:

class MyClass : private boost::noncopyable
{
    public:

    MyClass() {}
    virtual ~MyClass() {}
}

class OtherClass : private boost::noncopyable
{
    private:
    MyClass* m_pMyClass;
}

My thoughts are that MyClass cannot be copied using construction or assignment. Using a virtual destructor is needed if I want to support deriving classes from MyClass, which I do not want to support. I do not intend to create pointers to this class and pass them around.

I do not want a Singleton and I cannot see a downside to removing the virtual destructor.

Do I introduce a potential problem if remove the virtual destructor for a noncopyable class? Are there a better practices to handle a class that does not need to be a Singleton, but I only want one instance in another class and not support inheritance?

like image 340
TERACytE Avatar asked Jan 12 '10 20:01

TERACytE


People also ask

When should a class have a virtual destructor?

Virtual keyword for destructor is necessary when you want different destructors should follow proper order while objects is being deleted through base class pointer.

Why it's useful to set a class destructor as virtual?

Virtual destructors in C++ are used to avoid memory leaks especially when your class contains unmanaged code, i.e., contains pointers or object handles to files, databases or other external objects. A destructor can be virtual.

Should derived class destructor be virtual?

Note: in a derived class, if your base class has a virtual destructor, your own destructor is automatically virtual. You might need an explicitly defined destructor for other reasons, but there's no need to redeclare a destructor simply to make sure it is virtual.

In what situation does a destructor create virtual?

When destroying instances of a derived class using a base class pointer object, a virtual destructor is used to free up memory space allocated by the derived class object or instance. Note: Only Destructors can be Virtual.


1 Answers

No, the entire point of a virtual destructor is so derived classes can properly destruct polymorphically. If this will never be a base class, you don't need it to be virtual.

like image 125
Terry Mahaffey Avatar answered Sep 23 '22 16:09

Terry Mahaffey