Skip to main content
gamedev.net
🔒 Locked

Memory Allocation/Desallocation question

Started by ClementLuminy Aug 29, 2006 at 11:54 AM 1 replies 350+ views
Original Post
ClementLuminy
ClementLuminy
Hello I'm playing a little bit with polymorphysm in my program, and i was wondering something: Suppose i do something like that; class ClassA { int a; }; class ClassB: public class ClassA { int b; }; and then in my code: ... ClassA* ptr = (ClassA*)new ClassB; delete ptr ; .. Does the "delete A" free all the memory or does it only free the memory used by a class of type A .... In other word: do you think i will suffer of memory leaks with such a piece of code ? Thanks a lot !!! Clem
Fruny
Fruny
Quote:
Original post by ClementLuminy
Does the "delete A" free all the memory or does it only free the memory used by a class of type A ....

In other word: do you think i will suffer of memory leaks with such a piece of code ?


Since ClassA doesn't have a virtual destructor, your code has undefined behaviour. You could have a memory leak, or worse.

class ClassA{   int a;public:   <font color=blue>virtual ~ClassA() {}</font>};class ClassB:    public class ClassA{   int b;};...ClassA* ptr = new ClassB;  // The cast is unnecessary.delete ptr ;


Will be fine.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Zahlman
Zahlman
Also, in

class ClassB:    public class ClassA


the second 'class' is unnecessary (and quite unexpected by most programmers, at least from everything I've seen).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.