
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Class with Dynamically Allocated Objects
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 −
#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++)
#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() { ^