Archived

This topic is now archived and is closed to further replies.

kindfluffysteve

confusing issue with polymorthism

Recommended Posts

In java land one never bothered really about deleting instances of classes. but with c++ stuff looks tricky:
  
#include <stdio.h>

class ca{
public:
	ca(){
		val=new int[10];
	}

	~ca(){
		printf("ca destructor -deleting val\n");
		delete val;
	}

private:
	
	int *val;
};

class cb:Public ca{
public:
	cb():ca(){
		num=new int;
	}

	~cb(){
		printf("cb destructor - deleting num\n");
		delete num;
	}

private:
	int *num;

};

void main(){
//	ca *a;

	cb *b;
	ca *c;

	//a=new ca;

	b=new cb;
	c=b;

	delete c;
	delete b;
	//delete a;

}
   
when deleting - well the system still thinks c is a ca object when it comes to deleting. and in this case will cause a crash - but in general wont fully delete c. anybody know how to solve this issue other than delete (cb *)c because thats really messy. [edited by - kindfluffysteve on April 30, 2003 9:59:22 PM]

Share this post


Link to post
Share on other sites
Faradhi    122
With the line

c=b;

You''re just setting both pointers to point to the same object... c and b both point to the same object, so when you "delete c;", you''ve got b as a hanging pointer.

Press to test... *click* Release to detonate...

Share this post


Link to post
Share on other sites
risingdragon3    382
You also need to add virtual to your definition of your destructor. Something like this:
class a {.....
virtual ~a() {...}
};

class b : public a {
virtual ~b() {....}
};

Share this post


Link to post
Share on other sites
JimH    122
And just to be picky , besides the other two issues already mentioned, you also need to use the array version of delete in the destructor of ca.

Share this post


Link to post
Share on other sites
risingdragon3    382
I suppose I should mention why I totally didn''t above. It''s because the virtual distugishes at runtime which destructor to call, just like virtual void draw() works out at runtime which draw() function to call depending on the type.

Share this post


Link to post
Share on other sites