Results 1 to 1 of 1
Code:
#include <iostream>
#include <cstdlib>
using namespace std;
class myclass{
static int i;
int c;
public:
myclass() { c = i; cout<<"Inside constructor "<<i<<" "<<c<<endl; i++; }
myclass(myclass &m){ cout<<" ...
- 01-15-2011 #1Just Joined!
- Join Date
- Sep 2010
- Posts
- 4
Constructor and destructor calling for overloaded new and delete
As per my understanding when pointer p in the main is assigned with newly created class using overloaded new and then deleted with overloaded delete, constructor and destructor should be called once.Code:#include <iostream> #include <cstdlib> using namespace std; class myclass{ static int i; int c; public: myclass() { c = i; cout<<"Inside constructor "<<i<<" "<<c<<endl; i++; } myclass(myclass &m){ cout<<" dd "; } void* operator new(size_t s) throw(bad_alloc){ cout<<"Inside overloaded new "<<s<<endl; return malloc(s); // return ::new myclass; } void operator delete(void *m){ cout<<"Inside overloaded delete "<<i<<endl; // ::delete m ; // free((myclass *)m); ::delete (myclass*)m; // cout<<"Inside overloaded delete"<<endl; } ~myclass() { i--; cout<<"Inside destructor "<<i<<" "<<c<<endl; } }; int myclass::i =0; int main(){ //myclass mm; myclass *p = new myclass; // new myclass; cout<<" out "<<endl; //myclass *m = new myclass[10]; delete p; //delete []m; }
But an extra set of constructor and destructor are called in between if ::new myclass; is used in the overloaded new. Instead of ::new myclass; if return malloc(s); is used in the overloaded new, noticed an extra call to destructor.
Couldn't figure out the purpose of these unexpected calls.
Appreciate for any clarification. Thanks in Advance.
-GokulLast edited by MikeTbob; 01-15-2011 at 06:14 PM. Reason: Added Code Tags


Reply With Quote