Creating an object to a class only using new

Hi all,

I want to write a class which will allow to create an object only using new (Dynamic object creation) i.e., i should not be able to create a static object, how can i do this please guide me.
Make all constructors private, then write a friend function that returns a pointer to
a dynamically allocated instance.
Hi Smith,

Thanks a lot for your time.

I have tried that method, and also tried using static functions(Singleton) both are working fine. but i want to know whether C++ is providing any feature or there are any other ways to do this.
No, the above is the only way.
Thank you Smith.
Make all constructors private, then write a friend function that returns a pointer to
a dynamically allocated instance.


I usually dispense with friend and use a static class functions instead:

1
2
3
4
5
6
7
class Foo
{
public:
     static Foo * createInstance() { return new Foo(); }
private:
     Foo() {}
};
Last edited on
Topic archived. No new replies allowed.