Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C++ Moderated > Re: delete an i...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 2 of 7 Topic 9555 of 9775
Post > Topic >>

Re: delete an inherited class

by =?ISO-8859-1?Q?Daniel_Kr=FCgler?= <daniel.kruegler@[EMAIL PROTECTED] Apr 27, 2008 at 03:43 PM

On 27 Apr., 20:39, Free0...@[EMAIL PROTECTED]
 wrote:
> if i make a class that inherit another class, when i delete the
> pointer casted to the inherited class, only the destructor of the
> inherited class fires, the base class does not.
>
> ex:
>
> class shape
> {
>  ~shape()
> }
>
> class square : class shape
> {
>  ~square()
> }
>
> square pSquare = new square();
>
> shape pShape = dynamic_cast<shape *>(pSquare);
>
> delete pShape;  <== only calls  ~shape()

Please ensure that code snippets are valid
C++, otherwise it's hard to distinguish what
your actual problem is. Let's first transform
this into syntactically valid C++ (Your comments
imply that your program compiles):

class shape
{
public:
  ~shape(){}
};

class square : public shape
{
public:
  ~square(){}
};

int main() {
   square* pSquare = new square();

   shape* pShape = dynamic_cast<shape *>(pSquare);

   delete pShape; // <== only calls  ~shape()
}

Anything might happen in the very last statement,
because you are in "Undefined Behavior" land (something
like Alice's Wonderland, but not so funny ;-)

The rule behind this is [expr.delete]/3:

"In the first alternative (delete object), if the static
type of the operand is different from its dynamic type,
the static type shall be a base class of the operand’s
dynamic type and the static type shall have a virtual
destructor or the behavior is undefined.[..]"

In other words: If you want to perform a polymorphic
delete, the base class destructor must be virtual:

class shape
{
public:
  virtual ~shape(){}
};

HTH & Greetings from Bremen,

Daniel Krügler


-- 
      [ See http://www.gotw.ca/resources/clcm.htm
for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
 




 7 Posts in Topic:
delete an inherited class
Free0017@[EMAIL PROTECTED  2008-04-27 12:39:04 
Re: delete an inherited class
=?ISO-8859-1?Q?Daniel_Kr=  2008-04-27 15:43:41 
Re: delete an inherited class
Pavel Minaev <int19h@[  2008-04-27 15:46:19 
Re: delete an inherited class
alasham.said@[EMAIL PROTE  2008-04-27 15:46:32 
Re: delete an inherited class
=?UTF-8?B?RXJpayBXaWtzdHL  2008-04-27 15:48:23 
Re: delete an inherited class
Alexey Stepanyan <alex  2008-04-27 15:47:48 
Re: delete an inherited class
Vaclav Haisman <v.hais  2008-04-28 02:13:21 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Tue Jul 8 23:41:20 CDT 2008.