• Advertisement
Sign in to follow this  

Simple inheritence quesiton.

This topic is 4920 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hola. If I do this...
class COne
{
};

class CTwo: public COne
{
};

COne* pOne = (COne*)new CTwo;

delete pOne;


Will it delete the whole CTwo, or is it going to just delete the COne part and leak the CTwo portion of the class? Am I thinking too much? =)

Share this post


Link to post
Share on other sites
Advertisement
Since COne doesn't have a virtual destructor, the behaviour is undefined. Which is Standard-speak for "don't do this".

Share this post


Link to post
Share on other sites
The cast is unnecessary as CTwo is-a COne anyway.

The main problem would be if the classes had resources that they needed to manage. You should give COne a virtual destructor so that, when it is called through a base pointer, the derived destructor will be called first.

The cast doesn't have any effect on this behaviour. Casts in c++ are frowned upon on the whole. You'd usually only cast for borderline reasons such as for C APIs or reading from streams, networks etc.

In this case the following is just fine:

COne* pOne = new CTwo;
delete pOne;

edit: note I say 'this case' - on the whole you would be wise to put a virtual destructor in the base class.

Share this post


Link to post
Share on other sites
ok so this..


class COne
{
public:
COne(void) {}
virtual ~COne(void) {}

private:
int m_iSomeValue;
};

class CTwo: public COne
{
public:
CTwo(void) {}
virtual ~CTwo(void) {}

private:
int m_iSomeOtherValue;
};

COne* pOne = new CTwo;

delete pOne;






so that works?

Share this post


Link to post
Share on other sites
COne has a virtual destructor - no problem :)

Share this post


Link to post
Share on other sites
Yea, you'd only need virtual in COne, though I don't know if it would cause a problem.

Share this post


Link to post
Share on other sites
Quote:
Original post by Drakkcon
Yea, you'd only need virtual in COne, though I don't know if it would cause a problem.


No problem - when a member function is marked virtual, it stays virtual in derived classes. It would be hell if they didn't.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement