1.
Default Arguments in C++
a. In C++, default arguments can be provided for any function parameter by
assigning a value to the parameter in the function declaration. If the function is
called without an argument for that parameter, the default value is used.
However, once a default argument is given for a parameter, all subsequent
parameters must also have default arguments.
Here's a simple C++ example demonstrating default arguments:
#include <iostream>
using namespace std;
int sum(int x, int y, int z = 0, int w = 0) {
return (x + y + z + w);
int main() {
cout << sum(10, 15) << endl; // Outputs 25
cout << sum(10, 15, 25) << endl; // Outputs 50
cout << sum(10, 15, 25, 30) << endl; // Outputs 80
return 0;
}
2. Operator overloading using new and delete
The skeletons for the functions that overload new and delete are shown here:
// Allocate an object.
void *operator new(size_t size)
{
/* Perform allocation. Throw bad_alloc on failure.
Constructor called automatically. */
return pointer_to_memory;
// Delete an object.
void operator delete(void *p)
/* Free memory pointed to by p.
Destructor called automatically. */
Program on Operator overloading using new and delete keyword
The new operator is used to dynamically allocate
#include<iostream> memory on the heap for an object or an array of
#include<stdlib.h> objects. And delete operator is used to deallocate
the memory.
They allow the programmer to create and delete
using namespace std; variables in the program. The use of these
class student operators is essential for creating and managing
{
different program elements. These are also
helpful when debugging a program or removing
string name; invalid data from a program.
int age;
public:
student()
cout<< "Constructor is called\n" ;
student(string name, int age)
{
this->name = name;
this->age = age;
}
void display()
cout<< "Name:" << name << endl;
cout<< "Age:" << age << endl;
void * operator new(size_t size)
cout<< "Overloading new operator with size: " << size <<
endl;
void * p = ::operator new(size);
//void * p = malloc(size); will also work fine
return p;
}
void operator delete(void * p)
cout<< "Overloading delete operator " << endl;
free(p);
}
};
int main()
student * p = new student("Yash", 24);
p->display();
delete p;
}