Reputation: 31
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?
Upvotes: 3
Views: 464
Reputation: 76438
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.
Upvotes: 1
Reputation: 22152
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 fromstd::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
.
Upvotes: 1