How to make a C++ class whose objects can only be dynamically allocated?


In this problem we will see how we can make one class for which we can only create objects through dynamic memory allocation, no direct object creation is permitted.

The idea is simple. We have to create private destructor for that class. When the destructor is private, the compiler would produce a compiler error for non-dynamically allocated objects because compiler need to remove them from stack segment once they are not available for use. For dynamically allocated objects, the programmer is responsible for deleting object, but the compiler is not responsible for that, so it permits creating objects dynamically.

For avoiding memory leak, we will use a friend function which can be called by users of class for destroying object.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include<iostream>
using namespace std;
class NoDirectObjClass {
   private:
      ~NoDirectObjClass() {
         cout << "Destroyng NoDirectObjClass object" << endl;
      }
   public:
      NoDirectObjClass() {
         cout << "Creating object" << endl;
      }
   friend void friend_destructor(NoDirectObjClass* );
};
void friend_destructor(NoDirectObjClass* p) {
   delete p;
   cout << "Destroyng object using friend" << endl;
}
int main(){
   NoDirectObjClass *p = new NoDirectObjClass;
   friend_destructor(p);
}

Output

Creating object
Destroyng NoDirectObjClass object
Destroyng object using friend

If we try to make object directly, without using dynamic memory allocation, then it will generate output as follows −

Example (C++)

 Live Demo

#include<iostream>
using namespace std;
class NoDirectObjClass {
   private:
      ~NoDirectObjClass() {
         cout << "Destroyng NoDirectObjClass object" << endl;
      }
   public:
      NoDirectObjClass() {
         cout << "Creating object" << endl;
      }
   friend void friend_destructor(NoDirectObjClass* );
};
void friend_destructor(NoDirectObjClass* p) {
   delete p;
   cout << "Destroyng object using friend" << endl;
}
int main(){
   NoDirectObjClass t1;
}

Output

main.cpp: In function ‘int main()’:
main.cpp:22:22: error: ‘NoDirectObjClass::~NoDirectObjClass()’ is private
within this context
   NoDirectObjClass t1;
                     ^~
main.cpp:6:9: note: declared private here
         ~NoDirectObjClass() {
         ^

Updated on: 27-Aug-2020

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements