C++ | Misc C++ | Question 5

How can we make a C++ class such that objects of it can only be created using new operator?

If user tries to create an object directly, the program produces compiler error.
(A) Not possible
(B) By making destructor private
(C) By making constructor private
(D) By making both constructor and destructor private

Answer: (B)

Explanation: See the following example.

// Objects of test can only be created using new
class Test
    ~Test() {}
friend void destructTest(Test* );
// Only this function can destruct objects of Test
void destructTest(Test* ptr)
    delete ptr;
int main()
    // create an object
    Test *ptr = new Test;
    // destruct the object
    destructTest (ptr);
    return 0;

See https://www.geeksforgeeks.org/private-destructor/ for more details.

Quiz of this Question

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.

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.