Skip to main content

One way : Heap or Stack allocation

Took my time to find solution for this and it actually made me realize how much i have to learn.
Now question is how can we enforce the creation of objects whether on heap or stack.

Creating object on Heap only.
Make your destructor private and create a destroy function.
Class A
{
 ~A(){}
public:
 A(){}
void destroy() { delete this; }
}

Now if you can not create your object:

A a; //error: 'A::~A()' is private
A  a = new A();

Great. Now all the objects will be allocated to heap only. Making destructor private a better choice than constructor as we don't know number of constructor so early in programming.

Creating object on stack

While i knew that it has to do something with operator new, but could not figure out how can i create object on stack and return the memory back to class initialization.

Though answer was simple, i had to google for that:

Overload operator new, new[], operator delete and delete[] and make them private ;)

class A
{
private:
void *operator new(size_t size) { }
void * operator new[](size_t size) {}
void operator delete(void *p) {}
void operator delete[](void *p) {}
};

You can create the object like:

A a;//It will work.
A *a = new A();//Error

Comments

Popular posts from this blog

Car Parking Problem

There is n parking slots and n-1 car already parked. Lets say car parked with initial arrangement and we want to make the car to be parked to some other arrangement. Lets say n = 5, inital = free, 3, 4, 1, 2 desired = 1, free, 2, 4 ,3 Give an algorithm with minimum steps needed to get desired arrangement. Told by one of my friend and after a lot of search i really got a nice solution. I will post solution in comment part

Median of Five Numbers

U have 5 NOs , X1,X2,X3,X4,X5 With minimum no. of comparisons we have to find a median. SWAP(X,Y) function is available to u . I have a answer of six comparisons and eight swaps....wait for people to find out by themselves.

Merge two sorted array inplace

Given an integer array of which both first half and second half are sorted. Write a function to merge the two parts to create one single sorted array in place [do not use any extra space]. e.g. If input array is [1,3,6,8,-5,-2,3,8] It should be converted to: [-5,-2,1,3,3,6,8,8]