-
What is the output of this program?
#include <iostream>
#include <new>
#include<cstdlib>
using namespace std;
class OperatorX;
struct Node
{
OperatorX* data;
bool filled;
Node() : filled(false) { }
};
class OperatorX
{
static Node buffer[];
public:
int num;
enum { size = 3};
void* operator new(size_t sz) throw (const char*)
{
void* ptr = malloc(sz);
if (sz == 0)
throw "Error: malloc() failed";
cout << "Operator X :: new(size_t)" << endl;
return ptr;
}
void *operator new(size_t sz, int location) throw (const char*)
{
cout << "Operator X :: new(size_t, " << location << ")" << endl;
void* ptr = 0;
if (location < 0 || location >= size || buffer[location].filled == true)
{
throw "Error: buffer location occupied...";
}
else
{
ptr = malloc(sizeof(OperatorX));
if (ptr == 0)
throw "Error: Creating Operator X object failed";
buffer[location].filled = true;
buffer[location].data = (OperatorX*) ptr;
}
return ptr;
}
static void printbuffer()
{
for (int k = 0; k < size; k++)
{
cout << buffer[k].data->num << endl;
}
}
};
Node OperatorX::buffer[size];
int main()
{
try
{
OperatorX* ptrA = new OperatorX;
OperatorX* ptrB = new(0) OperatorX;
OperatorX* ptrC = new(1) OperatorX;
OperatorX* ptrD = new(2) OperatorX;
ptrB->num = 100;
ptrC->num = 101;
ptrD->num = 102;
OperatorX :: printbuffer();
OperatorX* ptrE = new(0) OperatorX;
}
catch (const char* message)
{
cout << message << endl;
}
}
-
- Operator X :: new(size_t)
Operator X :: new(size_t, 0)
Operator X :: new(size_t, 1)
Operator X :: new(size_t, 2)
100
101
102
Operator X :: new(size_t, 0)
Error: buffer location occupied... - Operator X :: new(size_t)
Operator X :: new(size_t, 0)
Operator X :: new(size_t, 1)
Operator X :: new(size_t, 2) - 100
101
102
Operator X :: new(size_t, 0)
Error: buffer location occupied... - Operator X :: new(size_t, 0)
Error: buffer location occupied... - All of above
- Operator X :: new(size_t)
Correct Option: A
In this program, We are giving a location to two variables in the program, So it is arising an exception.