Google News
logo
CPP - Quiz(MCQ)
How can a user make a c++class in such a way that the object of that class can be created only by using the new operator, and if the user tries to make the object directly, the program will throw a compiler error?
A)
Not possible
B)
By making the destructor private.
C)
By making the constructor private.
D)
By making both constructor and destructor private.

Correct Answer :   By making the destructor private.


Explanation :

One can make a c++ program in which a class's object can be created using only the " new "operator, and still, if the user wants and tries to create its object directly, the program will produce a compiler error. To can understand it more clearly, you can consider the following given example.
 
Example
 
// in this program, Objects of test can only be created using new
class Test1
{
private:
    ~Test1() {}
friend void destructTest1(Test1* );
};

// Only this function can destruct objects of Test1
voiddestructTest(Test1* ptr)
{
deleteptr;
}

int main()
{
    // create an object
    Test1 *ptr = new Test1;

    // destruct the object
    destructTest1 (ptr);

return 0;
}​

Advertisement