Class Quiz-Asked in Interviews

Placewit
2 min readDec 14, 2021

How can we make a C++ class such that objects of it can only be created using a new operator? If a user tries to create an object directly, the program produces a compiler error.

A) Not Possible

B) By making destructor private

C) By making constructor private

D) By making both constructor and destructor private

Solution:

B) is Correct

This code snippet explains the solution

// Objects of test can only be created using new
class Test
{
private:
~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;
}

Thanks for Reading

Placewit grows the best engineers by providing an interactive classroom experience and by helping them develop their skills and get placed in amazing companies.

Learn more at Placewit. Follow us on Instagram and Facebook for daily learning.

--

--