Thursday, 21 June 2018

opertor new

The new operator does both the allocation and the initialization, where as the operator new only does the allocation.


class car
{
    string name;
    int num;
 
    public:
 
        car(string a, int n)
        {
            cout << "Constructor called" << endl;
            this->name = a;
            this->num = n;
        }
 
                
        void *operator new(size_t size)
        {
            cout << "new operator overloaded" << endl;
            void *p = malloc(size);
            return p;
        }
 
        void operator delete(void *ptr)
        {
            cout << "delete operator overloaded" << endl;
            free(ptr);
        }
};
 
int main()
{
    car *p = new car("HYUNDAI", 2012);
    delete p;
}

  • It is the mechanism of overriding the default heap allocation logic.
  • It doesn’t initializes the memory i.e constructor is not called. However, after our overloaded new returns, the compiler then automatically calls the constructor also as applicable.

No comments:

Post a Comment