Consider the following fully functioning example:
#include <iostream>
#include <memory>
class A {
public:
A() {
std::cout << "A() \n";
}
~A() {
std::cout << "~A \n";
}
};
class B:public A {
public:
B() {
std::cout << "B() \n";
}
~B() {
std::cout << "~B() \n";
}
};
int main() {
std::cout << "Output: \n";
{
std::unique_ptr<A> TestB(new B());
}
return 0;
}
The output is:
Output:
A()
B()
~A
Is there any way for B's destructor to be called with inheritance like this? I was not aware that unique_ptrs also have slicing problem. Of course I can use std::unique_ptr<B> but I wanted to have a std::vector<std::unique_ptr<A>> and add inherited items.
Is there a way to have a list of std::unique_ptrs in combination with inheritance?
When you say delete p; and the type of the most-derived object containing *p (colloquially "the dynamic type of *p") is not the same as the static type of *p, then the behaviour is undefined if the static type of *p is a class-type and does not have a virtual destructor.
To fix this, you need to say virtual ~A().
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