Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unique_ptr of base class holding reference of derived class does not show warning in gcc compiler while naked pointer shows it. Why?

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.

like image 546
gaurav bharadwaj Avatar asked Apr 25 '19 12:04

gaurav bharadwaj


People also ask

Can a base class pointer contains the reference of its derived class?

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.

Does base class have access to derived class?

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.


1 Answers

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.

like image 144
Michael Kenzel Avatar answered Sep 23 '22 06:09

Michael Kenzel