Find the answer to your Linux question:
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<<" ...
  1. #1
    Just Joined!
    Join Date
    Sep 2010
    Posts
    4

    Constructor and destructor calling for overloaded new and delete

    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;
    
    
    }
    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.

    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.


    -Gokul
    Last edited by MikeTbob; 01-15-2011 at 06:14 PM. Reason: Added Code Tags

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...