Sign in to follow this  
GeekPlusPlus

Simple inheritence quesiton.

Recommended Posts

GeekPlusPlus    124
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
Fruny    1658
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
petewood    819
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
GeekPlusPlus    124
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
Fruny    1658
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this