0
class Base
{
int n;
public:
    Base(int n)
        : n(n)
    {}
       ...
}

class Derived : Base
{
public:
    Derived(int n)
        : Base(n)
    {}
}

void function()
{
    Derived* obj  = new Derived(10);

       ...

    delete obj;
}

I have a similar situation as with the above code, where Derived is just a wrapper of Base. To access the object in function I’m using a Derived pointer on purpose. My understanding is that the whole object it’s allocated on the heap, including the Base part and that delete reclaims all the memory, even if I use a Derived pointer and Base is not polymorphic. Is this correct or there is something more to it ?

Thanks

  • Correct. The other cases would be described here: https://stackoverflow.com/questions/16498332/does-delete-work-properly-with-polymorphism?noredirect=1&lq=1 – Captain Giraffe Feb 26 '18 at 02:22
  • What's the point of allocating the object on the heap? Unless there is a good reason (there are some) you are best off to use a value of the object on the stack (and if it goes on the heap, use a smart pointer, most likely `std::unique_ptr` to get it cleaned up). – Dietmar Kühl Feb 26 '18 at 02:24
  • 2
    @CaptainGiraffe: I don't like this question you pointed at as duplicate: primarily, the code is full of undefined behaviour (manually explicitly destroying an object on the stack results in double destruction). – Dietmar Kühl Feb 26 '18 at 02:29
  • @Captain Giraffe It's not a duplicate as the questions pointed out by you are explicitly using base pointer to access the object. – Antonio Molinaro Feb 26 '18 at 02:51
  • @Dietmar Kühl what's the point ? Getting a deep knowledge of c++ and not just using other peoples ideas without knowing what's in it. – Antonio Molinaro Feb 26 '18 at 03:45
  • @Captain Giraffe Please, put your first comment as answer so that I can accept it and close the question. Thanks. – Antonio Molinaro Feb 27 '18 at 00:58

0 Answers0