Creating an object to a class only using new

Apr 12, 2010 at 12:27pm
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.
Apr 12, 2010 at 2:25pm
Make all constructors private, then write a friend function that returns a pointer to
a dynamically allocated instance.
Apr 13, 2010 at 3:35am
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.
Apr 13, 2010 at 12:43pm
No, the above is the only way.
Apr 15, 2010 at 3:15am
Thank you Smith.
Apr 15, 2010 at 3:07pm
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 Apr 15, 2010 at 3:07pm
Topic archived. No new replies allowed.