C++ Program : How to Prevent an object being created on Stack.

// We can even make constructor of a class as private, not to create object on stack.
// But constructor has many variants. like constructor with no argument, constructor with arguments.
// So, we made destructor as private. Because Destructor will be only one per class.

// Prevent Creating Object on Stack
// Declare Destructor of a class as Private/Protected.
#include<iostream>
using namespace std;

class base
{
    public:
        base(int a)
        {
            cout<<"Parameter Constructor\n";
        }
        base()
        {
            cout<<"Constructor\n";
        }   
        void destroy()
        {
            delete this;
        }
    private:
        ~base();
};

base::~base()
{
    cout<<"Destructor\n";
}

int main()
{
    base *b = new base(10);;
    b->destroy();

    base *bb = new base;
}

Comments

Popular posts from this blog

C++ Guidelines for Multithreaded System

Signalling System #7(SS7) Protocol.

std::shared_ptr