1

Trying to create c++ interface, testing now.

/*
 * Simple interface tests
*/


#include <iostream>

using namespace std;

class Shape {
    public:
    virtual int area() = 0;
};

class Square: public Shape {
    public:
    int side;
    int height;

    Square (int a, int b){
        side = a;
        height = b;
    }

    ~Square(){cout << "destructor" << endl;}

    int area(){
        return side * height;}
};


int main(int argc, char **argv){    
    {
    Shape * s1 = new Square(2, 2);
    cout << s1->area() << endl;
    delete s1;
    }
    return 0;
}

Destructor seems not working and I'm deleting the pointer only. Is this a memory leak? If yes how to avoid it? Of course if I do:
Square s1(2,2);
Then is fine, but I'm not sure what's happening when creating pointer to the abstract Shape class.

Tom
  • 55
  • 7
  • This should help: https://stackoverflow.com/a/461224/6610379 – Phil Brubaker Nov 21 '18 at 13:58
  • 2
    It's not actually a memory leak - but your destructor is not `virtual`, so you are only calling the base class (`Shape`) destructor, the same as if you had forgotten to make `area()` `virtual`. – BoBTFish Nov 21 '18 at 13:58
  • Does it change anything adding destructor to the ```Shape``` class? – Tom Nov 21 '18 at 14:06
  • As `Shape` doesn't have a virtual destuctor, `delete s1` calls `s1->Shape::~Shape()` and frees memory. If you checked the assembler code generated by a compiler you would see that exact address `Shape::~Shape()` is used for `call` instruction. If you had virtual destructor for `Shape`, you would see that the destructor address is retrieved from virtual methods table, i.e. choosen dynamically at runtime. – Artem Razin Nov 22 '18 at 10:41

0 Answers0