1.

When Should Overload New Operator On A Global Basis Or A Class Basis?

Answer»

Answer :We overload operator new in our PROGRAM, when we want to INITIALIZE a data item or a CLASS object at the same place where it has been allocated memory. The following example shows how to overload new operator on global basis. #include #include void * operator new ( size_t s ) { void *q = malloc ( s ) ; return q ; } void main( ) { INT *p = new int ; *p = 25 ; cout << *p ; } When the operator new is overloaded on global basis it becomes impossible to initialize the data members of a class as different classes may have different types of data members. The following example shows how to overload new operator on class-by-class basis. #include #include class sample { int i ; public : void* operator new ( size_t s, int ii ) { sample *q = ( sample * ) malloc ( s ) ; q -> i = ii ; return q ; } } ; class sample1 { float f ; public : void* operator new ( size_t s, float FF ) { sample1 *q = ( sample1 * ) malloc ( s ) ; q -> f = ff ; return q ; } } ; void main( ) { sample *s = new ( 7 ) sample ; sample1 *s1 = new ( 5.6f ) sample1 ; } Overloading the operator new on class-by-class basis makes it possible to allocate memory for an object and initialize its data members at the same place.



Discussion

No Comment Found