I have a hierarchy of base class and derived class. Base class has one virtual function which is overridden by derived class.
class Base { public: ~Base(); virtual void other_functionality() = 0; }; class Derived : public Base { public: ~Derived (); void other_functionality() {//some code}; };
Now if i do like this:
int main() { Base * P = new Derived (); delete p; return 0; }
It gives error:
deleting object of polymorphic class type which has non-virtual destructor.
But with unique_ptr it passes without warning.
int main() { std::unique_ptr<Base> p; p.reset(new Derived ()); return 0; }
I know if I use virtual destructor. Warning with naked pointer will be solved. But question remains - why absence of virtual destructor shows problem with naked pointer and not with unique_ptr.
Explanation: A base class pointer can point to a derived class object, but we can only access base class member or virtual functions using the base class pointer because object slicing happens when a derived class object is assigned to a base class object.
A base class's private members are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class.
Well, first of all, deleting a derived object through a base pointer when the base class does not have a virtual destructor is undefined behavior. Compilers are not required to diagnose undefined behavior…
That being said, the reason why this warning does not appear when using std::unique_ptr
is most likely due to the fact that GCC does not report warnings that would appear in system headers.
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