0

Let's say that I have a base class X with only one virtual function.

I extend it to Y and override that function.

I didn't provide explicit destructor for X and Y.

What happens during the destruction in this statement.

Y y;
X *x= &y;
return;
.
.
.
X*x = new Y;
delete x;
return;

Which will cause memory leak..

Quentin
  • 62,093
  • 7
  • 131
  • 191
Yashwanth CB
  • 194
  • 1
  • 14
  • Neither? Also I don't see how these two code snippets on their own are related to virtual destructors? You'd need to at least show the class definitions. – UnholySheep Nov 16 '16 at 16:26
  • 1) No problem. x is just a pointer, but y gets destructed and frees all resources from super class too. 2) Resources of Y get lost, because just the destructor of X is called on an instance of Y in memory -> possible memory leak (or worse). – Youka Nov 16 '16 at 16:27
  • @UnholySheep there is nothing special about class definition. I mentioned the statement. The second one seems to cause a memory leak – Yashwanth CB Nov 16 '16 at 16:37

1 Answers1

0
Y y;
X *x = &y;
return;

Nothing bad happens here. The object y is (fully) destroyed at the end of its scope.

X*x = new Y;
delete x;
return;

This will cause a memory leak if you're lucky. The behavior is undefined, meaning anything bad could happen.

It's generally a good idea to declare a virtual destructor whenever the class is intended to be a base class for other classes.

aschepler
  • 70,891
  • 9
  • 107
  • 161