// Global new and delete operator
void * operator new(size_t size)
{
cout<< "Overloading new operator with size: " << size << endl;
void * p = malloc(size);
return p;
}
void operator delete(void * p)
{
cout<< "Overloading delete operator " << endl;
free(p);
}
class Details
{
int marks;
int rollno;
public:
Details( int marks, int rollno) : marks(marks), rollno(rollno)
{
cout << "Details Constructor called" << endl;
}
void display()
{
cout<< "Marks:" << marks << endl;
cout<< "rollno:" << rollno << endl;
}
~Details() { cout << "Details Destructor called" << endl;}
};
class student
{
string name;
int age;
Details* d;
public:
student()
{
cout<< "Constructor is called\n" ;
}
student(string name, int age, int marks, int rollno) : name{name},age{age}
{
cout << " Student Constructor called" << endl;
d = new Details{marks, rollno};
}
void display()
{
cout<< "Name:" << name << endl;
cout<< "Age:" << age << endl;
d->display();
}
~student() { cout << " Student Destructor called" << endl; delete d;}
};
// Driver function
int main()
{
student * p = new student("Yash", 24 , 5, 1);
p->display();
delete p;
}
Output:
Overloading new operator with size: 29
Overloading new operator with size: 24
Student Constructor called
Overloading new operator with size: 8
Details Constructor called
Name:Yash
Age:24
Marks:5
rollno:1
Student Destructor called
Details Destructor called
Overloading delete operator
Overloading delete operator
Overloading delete operator
I expected new and delete opeator functions to be called 2 times (for student and details). But output of the Program shows new and delete operator functions gets called 3 times. Why ?
Aucun commentaire:
Enregistrer un commentaire