C++ virtual destructor inheirtance from std::vector - c++

So I'm studying for an C++ exam and I've come across the following question:
If you were to inherit from std::vector would you create a virtual
destructor?
Since std::vector does not have a virtual destructor would there be any point in me creating one?

I think std::vector is a red herring. First let me rewrite the question as
If you were to write a class A that inherits from std::vector, would you give it a virtual destructor?
Then the only relevant thing here is whether std::vector does already have a virtual destructor. If it had, the destructor of A would always be virtual automatically, no matter whether you specify it with the virtual keyword or not. But std::vector does not have a virtual destructor. So the reference to it can be dropped:
If you were to write a class A, would you give it a virtual destructor?
The answer would still be that it will be automatically virtual if A inherits from any other class with virtual destructor, so the only interesting case left is:
If you were to write a class A, which does not inherit from any class with virtual destructor, would you give it a virtual destructor?
Now this is a very general question and as mentioned in the comments, it depends on whether you intend to use the class as polymorphic base, i.e. whether you want to allow deletion of objects of a type derived from A through a pointer/reference to A.

A class needs a virtual destructor if your design calls for deleting an object of a type derived from that class through a pointer to that class. That is,
class base {
};
class derived : public base {
};
void f() {
base *bp = new derived;
delete bp; // undefined behavior: base does not have a virtual destructor
}
std::vector, by design does not have a virtual destructor. It is not intended to be used as a base class.
So if your (flawed) design calls for deriving from std::vector<whatever> and deriving from your derived type and deleting objects of your ultimate type through pointers to your base type, then your base type must have a virtual destructor. But that has nothing to do with std::vector or with the fact that your base type is derived from std::vector. It's needed because of the way your base class is used.

Related

Base class has no destructor, but derived class does. Do I need to look for any pitfalls that DON'T relate to the heap?

In terms of inheritance, I understand that it's advised for your classes' destructors to be virtual, so the base class's destructor gets called correctly in addition to any derived destructors. However, I'm wondering if there are any stack-related issues that relate to derived objects in the following scenario.
Let's suppose we have a Base class that doesn't have a destructor (for whatever reason):
class Base{};
and a Derived class that DOES have a destructor:
class Derived : public Base
{
~Derived(){}
};
And in the main...:
int main()
{
Derived a;
return 0;
}
Do I run into any issues from the Base class not having a destructor? My initial guess is that the compiler will just generate a default destructor for the Base class. Again, my question is mostly related to the stack rather than dynamic memory: is there any weirdo scenario I need to look out for in order to avoid a Derived destructor being called and the Base destructor is not?
The rule you're thinking of is that if you delete an object of a derived type through a pointer to one of its base types and that base type does not have a virtual destructor the behavior is undefined. The code here doesn't delete anything, so the rule does not apply.
To ensure safety, it is sufficient that every destructor (implicit or explicit) be at least one of:
virtual (for base classes if you need to delete subclass instances through base class pointers)
protected (to ensure that it is impossible to attempt to delete through a base class pointer)
final (actually an attribute of the class, to avoid the entire possibility of subclasses).
There are a few rare edge cases where it is possible to safely call destructors, but they are generally a sign of bad design and are easy to avoid if you manage to happen across one of them.
As an aside, note that std::shared_ptr type-erases its deleter, so std::shared_ptr<Base> will work even if Base does not have a public destructor.
Your base class has an implicit destructor. All will be fine.
A virtual base class destructor is used to allow a derived constructor to run when destructing via a pointer or reference to the base class. So in your case, this would be unsafe:
void destruct(Base &b) { b.~Base(); }
Derived d; destruct(d);
But this will be perfectly safe:
void destruct(Derived &d) { d.~Derived(); }
Derived d; destruct(d);

Is it safe to initialize an auto_ptr with a pointer to a derived class?

Lets say I have a base class and a derived class:
class Base
{
public:
virtual ~Base() {}
virtual void DoSomething() = 0;
};
class Child : public Base
{
public:
virtual void DoSomething()
{
// Do Something
}
};
Is it safe to initialize an std::auto_ptr of the type of the base class with a pointer to an instance of the derived class? I.E. will an object created like this:
std::auto_ptr<Base> myObject(new Derived());
correctly call the destructor of the derived class instead of the base class without leaking memory?
Despite the fact that you shouldn't use std::auto_ptr anymore since the arrival of C++11;
Yes, this is safe as long as your base has a virtual destructor.
Without the virtual destructor on the base, (like Steve Jessop noted below) you would get undefined behavior, since the destructor of the deriving class would be unknown at the time of destruction, and hence not being executed. This is a dangerous problem since in many cases it stays unnoticed. E.g., if you would manage some kind of resource in a single-inheritance class, that should have been freed in the destructor, a leak would occur silently.
Perfectly safe.
Many references are available - try searching for "auto_ptr polymorphism".
e.g. http://www.devx.com/tips/Tip/14391
As long as your class Base the std::auto_ptr<Base> is parameterized with has a virtual destructor you can initialize the std::auto_ptr<Base> with classes derived of Base and they will be properly destroyed if the std::auto_ptr<Base> destructor is instantiated when a definition of Base is visible.

why to declare a virtual destructor C++? [duplicate]

I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare virtual destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.
It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify one), not the derived class's destructor. Instant memory leak.
For example
class Interface
{
virtual void doSomething() = 0;
};
class Derived : public Interface
{
Derived();
~Derived()
{
// Do some important cleanup...
}
};
void myFunc(void)
{
Interface* p = new Derived();
// The behaviour of the next line is undefined. It probably
// calls Interface::~Interface, not Derived::~Derived
delete p;
}
The answer to your question is often, but not always. If your abstract class forbids clients to call delete on a pointer to it (or if it says so in its documentation), you are free to not declare a virtual destructor.
You can forbid clients to call delete on a pointer to it by making its destructor protected. Working like this, it is perfectly safe and reasonable to omit a virtual destructor.
You will eventually end up with no virtual method table, and end up signalling your clients your intention on making it non-deleteable through a pointer to it, so you have indeed reason not to declare it virtual in those cases.
[See item 4 in this article: http://www.gotw.ca/publications/mill18.htm]
I decided to do some research and try to summarise your answers. The following questions will help you to decide what kind of destructor you need:
Is your class intended to be used as a base class?
No: Declare public non-virtual destructor to avoid v-pointer on each object of the class *.
Yes: Read next question.
Is your base class abstract? (i.e. any virtual pure methods?)
No: Try to make your base class abstract by redesigning your class hierarchy
Yes: Read next question.
Do you want to allow polymorphic deletion through a base pointer?
No: Declare protected virtual destructor to prevent the unwanted usage.
Yes: Declare public virtual destructor (no overhead in this case).
I hope this helps.
* It is important to note that there is no way in C++ to mark a class as final (i.e. non subclassable), so in the case that you decide to declare your destructor non-virtual and public, remember to explicitly warn your fellow programmers against deriving from your class.
References:
"S. Meyers. More Effective C++, Item 33 Addison-Wesley, 1996."
Herb Sutter, Virtuality, 2001
C++ Faq, 20.7, "When should my destructor be virtual?"
The answers to this question, of course.
Yes it is always important. Derived classes may allocate memory or hold reference to other resources that will need to be cleaned up when the object is destroyed. If you do not give your interfaces/abstract classes virtual destructors, then every time you delete a derived class instance via a base class handle your derived class' destructor will not be called.
Hence, you're opening up the potential for memory leaks
class IFoo
{
public:
virtual void DoFoo() = 0;
};
class Bar : public IFoo
{
char* dooby = NULL;
public:
virtual void DoFoo() { dooby = new char[10]; }
void ~Bar() { delete [] dooby; }
};
IFoo* baz = new Bar();
baz->DoFoo();
delete baz; // memory leak - dooby isn't deleted
It is not always required, but I find it to be good practice. What it does, is it allows a derived object to be safely deleted through a pointer of a base type.
So for example:
Base *p = new Derived;
// use p as you see fit
delete p;
is ill-formed if Base doesn't have a virtual destructor, because it will attempt to delete the object as if it were a Base *.
It's not only good practice. It is rule #1 for any class hierarchy.
The base most class of a hierarchy in C++ must have a virtual destructor
Now for the Why. Take the typical animal hierarchy. Virtual destructors go through virtual dispatch just as any other method call. Take the following example.
Animal* pAnimal = GetAnimal();
delete pAnimal;
Assume that Animal is an abstract class. The only way that C++ knows the proper destructor to call is via virtual method dispatch. If the destructor is not virtual then it will simply call Animal's destructor and not destroy any objects in derived classes.
The reason for making the destructor virtual in the base class is that it simply removes the choice from derived classes. Their destructor becomes virtual by default.
The answer is simple, you need it to be virtual otherwise the base class would not be a complete polymorphic class.
Base *ptr = new Derived();
delete ptr; // Here the call order of destructors: first Derived then Base.
You would prefer the above deletion, but if the base class's destructor is not virtual, only the base class's destructor will be called and all data in derived class will remain undeleted.

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?
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.
The general rule is if your class has virtual functions it needs a virtual destructor. If it doesn't, but is still derived from a base class, the base class (and hence your class) may or may not need a virtual destructor depending.
Deriving your class from boost::noncopyable doesn't really count as being derived from a base class. boost::noncopyable is more like a convenient annotation backed up with a couple of declarations that will cause the compiler to enforce the annotation. It's not really a base class in any conventional sense. Nobody is ever going to try to pass around a pointer to your class as a pointer or reference to boost::noncopyable. And even if they did your virtual destructor wouldn't help because the boost::noncopyable's destructor isn't.
And lastly, as was pointed out in a comment, you are even privately inheriting from boost::noncopyable so it's not even really inheritance at all as far as anybody outside the class is concerned.
So really, no need to make it a virtual destructor.
I'm really not a fan of the boost::noncopyable class as a whole. Why not just declare your class's copy constructor and assignment operator private and not define them. That will accomplish the same thing, and you can ditch the virtual destructor.
Boost only supplies a virtual destructor so that people can pass around boost::noncopyable objects polymorphic and still have them behave well. Technically speaking if you are not going to use the class polymorphically (you can even still inherit from it), you really don't need a virtual destructor.
Virtual destructor in base class is used to avoid partial destruction problem like :
Base *pBase = new Derived();
delete pBase;
//if destructor is not made virtual then derived class destructor will never called.
When you inherit a class privately , compiler won't perform implicit casting from derived to base class and if you are sure that derived object is never destructed using base class pointer then you don't need virtual destructor in base class.
Base *pBase = new Derived(); // will flash error
boost::noncopyable is meant to say that you don't want copies of the object made. You're aware that this is different from deriving from the object.
It is perfectly fine to get rid of the virtual destructor if you won't ever derive from the object. If you want to enforce the "don't derive from this object" policy, there is a way. Unfortunately, there is no boost::nonderivable to pretty this up for you.
As mentioned in the link, C++11 allows you to declare the class final:
class MyClass : final private boost::noncopyable { ... };

Why should I declare a virtual destructor for an abstract class in C++?

I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare virtual destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.
It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify one), not the derived class's destructor. Instant memory leak.
For example
class Interface
{
virtual void doSomething() = 0;
};
class Derived : public Interface
{
Derived();
~Derived()
{
// Do some important cleanup...
}
};
void myFunc(void)
{
Interface* p = new Derived();
// The behaviour of the next line is undefined. It probably
// calls Interface::~Interface, not Derived::~Derived
delete p;
}
The answer to your question is often, but not always. If your abstract class forbids clients to call delete on a pointer to it (or if it says so in its documentation), you are free to not declare a virtual destructor.
You can forbid clients to call delete on a pointer to it by making its destructor protected. Working like this, it is perfectly safe and reasonable to omit a virtual destructor.
You will eventually end up with no virtual method table, and end up signalling your clients your intention on making it non-deleteable through a pointer to it, so you have indeed reason not to declare it virtual in those cases.
[See item 4 in this article: http://www.gotw.ca/publications/mill18.htm]
I decided to do some research and try to summarise your answers. The following questions will help you to decide what kind of destructor you need:
Is your class intended to be used as a base class?
No: Declare public non-virtual destructor to avoid v-pointer on each object of the class *.
Yes: Read next question.
Is your base class abstract? (i.e. any virtual pure methods?)
No: Try to make your base class abstract by redesigning your class hierarchy
Yes: Read next question.
Do you want to allow polymorphic deletion through a base pointer?
No: Declare protected virtual destructor to prevent the unwanted usage.
Yes: Declare public virtual destructor (no overhead in this case).
I hope this helps.
* It is important to note that there is no way in C++ to mark a class as final (i.e. non subclassable), so in the case that you decide to declare your destructor non-virtual and public, remember to explicitly warn your fellow programmers against deriving from your class.
References:
"S. Meyers. More Effective C++, Item 33 Addison-Wesley, 1996."
Herb Sutter, Virtuality, 2001
C++ Faq, 20.7, "When should my destructor be virtual?"
The answers to this question, of course.
Yes it is always important. Derived classes may allocate memory or hold reference to other resources that will need to be cleaned up when the object is destroyed. If you do not give your interfaces/abstract classes virtual destructors, then every time you delete a derived class instance via a base class handle your derived class' destructor will not be called.
Hence, you're opening up the potential for memory leaks
class IFoo
{
public:
virtual void DoFoo() = 0;
};
class Bar : public IFoo
{
char* dooby = NULL;
public:
virtual void DoFoo() { dooby = new char[10]; }
void ~Bar() { delete [] dooby; }
};
IFoo* baz = new Bar();
baz->DoFoo();
delete baz; // memory leak - dooby isn't deleted
It is not always required, but I find it to be good practice. What it does, is it allows a derived object to be safely deleted through a pointer of a base type.
So for example:
Base *p = new Derived;
// use p as you see fit
delete p;
is ill-formed if Base doesn't have a virtual destructor, because it will attempt to delete the object as if it were a Base *.
It's not only good practice. It is rule #1 for any class hierarchy.
The base most class of a hierarchy in C++ must have a virtual destructor
Now for the Why. Take the typical animal hierarchy. Virtual destructors go through virtual dispatch just as any other method call. Take the following example.
Animal* pAnimal = GetAnimal();
delete pAnimal;
Assume that Animal is an abstract class. The only way that C++ knows the proper destructor to call is via virtual method dispatch. If the destructor is not virtual then it will simply call Animal's destructor and not destroy any objects in derived classes.
The reason for making the destructor virtual in the base class is that it simply removes the choice from derived classes. Their destructor becomes virtual by default.
The answer is simple, you need it to be virtual otherwise the base class would not be a complete polymorphic class.
Base *ptr = new Derived();
delete ptr; // Here the call order of destructors: first Derived then Base.
You would prefer the above deletion, but if the base class's destructor is not virtual, only the base class's destructor will be called and all data in derived class will remain undeleted.