+ 2
Question
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 produce error? 1_ by making both contructor and destructor private 2_ by making destructor private 3_ by making constructor private
1 Answer
+ 2
You need a pure virtual function and a class that inherits your base class, so that the base class becomes abstract and can be used just to create pointers.
You see, even new calls the constructor and if you try calling this in main for an object of YourClass, when all its constructors are private, you will get an error:
YourClass* obj = new YourClass;
// Error - Initializer is private!
So, create your class like this:
class A // Just the abstract class
{
public:
virtual void fx_1() =0;
virtual void fx_2() =0;
... // More functions that you may
//need, but atleast one of them
// should be of the format
// above (pure virtual).
};
class B : public A
{
public:
void fx_1() {...}
void fx_2() {...}
// All functions that have the pure virtual form must be redeclared.
}
int main()
{
A* obj = new B; // You need it to act like a B object, not an A object.
obj -> fx_1();
// With this,you can never create an object of type A, just a pointer to it, and even that pointer can't point to an object of type A, but its derived members only.
}
If you don't want to do this, you may declare public static functions get and set to create instances for you using a private constructor. But that won't use new directly in main.