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 > overriding new ...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 1 of 3 Topic 9824 of 9984
Post > Topic >>

overriding new and delete operators...and didn't work as I expected

by hongseok.yoon@[EMAIL PROTECTED] Jul 24, 2008 at 02:38 AM

I have code like bellow...

class AncestorClass
{
public:
	AncestorClass()	{}

	virtual ~AncestorClass()	{}

	static void* operator new(size_t _size)
	{
		cout << "AncestorClass new" << endl;
		AncestorClass*	_ptr	= ::new AncestorClass();
		if (_ptr)	_ptr->Initialize();
		return _ptr;
	}
	static void operator delete(void* _ptr)
	{
		cout << "AncestorClass delete" << endl;
		if (_ptr)	((AncestorClass*)_ptr)->Finalize();
		::delete	_ptr;
	}

	virtual void	Initialize()
	{
		cout	<< "Ancestor Initialize" << endl;
	}

	virtual void	Finalize()
	{
		cout	<< "Ancestor Finalize" << endl;
	}
};

class DerivedClass : public AncestorClass
{
public:
	DerivedClass()	{}

	virtual ~DerivedClass()	{}

	static void* operator new(size_t _size)
	{
		cout << "DerivedClass new" << endl;
		DerivedClass*	_ptr	= ::new DerivedClass();
		if (_ptr)	_ptr->Initialize();
		return _ptr;
	}
	static void operator delete(void* _ptr)
	{
		cout << "DerivedClass delete" << endl;
		((DerivedClass*)_ptr)->Finalize();
		::delete _ptr;
	}

	virtual void	Initialize()
	{
		cout	<< "DerivedClass Initialize" << endl;
	}

	virtual void	Finalize()
	{
		cout	<< "DerivedClass Finalize" << endl;
	}
};

int main()
{
	AncestorClass*	t	= new DerivedClass;
	delete	t;

	return 0;
}

What I expected result is...

DerivedClass new
DerivedClass Initialize
DerivedClass delete
DerivedClass Finalize

but what in real is...

DerivedClass new
DerivedClass Initialize
DerivedClass delete
AncestorClass Finalize

Where's my problem and how to fix it?

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




 3 Posts in Topic:
overriding new and delete operators...and didn't work as I expec
hongseok.yoon@[EMAIL PROT  2008-07-24 02:38:06 
Re: overriding new and delete operators...and didn't work as I
Tony Delroy <tony_in_d  2008-07-24 05:58:25 
Re: overriding new and delete operators...and didn't work as I e
Thomas Richter <thor@[  2008-07-24 05:58:30 

Post A Reply:
  Go here to Signup

AddThis Feed Button


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

Contact
tan12V112 Sun Sep 7 8:33:17 CDT 2008.