The problem is to create a class such that the non-dynamic allocation of object causes compiler error. For example, create a class ‘Test’ with following rules.
The idea is to create a private destructor in the class. When we make a private destructor, the compiler would generate a compiler error for non-dynamically allocated objects because compiler need to remove them from stack segment once they are not in use.
Since compiler is not responsible for deallocation of dynamically allocated objects (programmer should explicitly deallocate them), compiler won’t have any problem with them. To avoid memory leak, we create a friend function destructTest() which can be called by users of class to destroy objects.
Object Created Destroying Object Object Destroyed
If we don’t want to create a friend function, we can also overload delete and delete operators in Test, this way we don’t have to call a specific function to delete dynamically allocated objects.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to dynamically allocate a 2D array in C?
- Read/Write Class Objects from/to File in C++
- How to restrict dynamic allocation of objects in C++?
- When are static objects destroyed?
- C++ Classes and Objects
- Comparing String objects using Relational Operators in C++
- Count the number of objects using Static member function
- How to initialize Array of objects with parameterized constructors in C++
- Introduction to Complex Objects and Composition
- Life cycle of Objects in C++ with Example
- Passing and Returning Objects in C++
- How to convert a class to another class type in C++?
- Difference between Base class and Derived class in C++
- Can a C++ class have an object of self type?
- Can we access private data members of a class without using a member or a friend function?
- Change/add only one character and print '*' exactly 20 times
- Print a long int in C using putchar() only
- Print pattern using only one loop | Set 1 (Using setw)
- Why only subtraction of addresses allowed and not division/addition/multiplication
- Find the node whose sum with X has minimum set bits