any ideas?
thanks

Recommended Answers

All 4 Replies

Not possible. The programmer can create it either on the stack or on the heap -- the choice is up to him/her. The object has no idea where it is in memory.

A simple way:

struct A
{
    static A* create() { return new A() ; }
    
    // ...

    private:
        A( /* ... */ ) ;
        A( const A& that ) ;
        // ...
};

If that is too simple for your requirements, see:
Item 27: Requiring or prohibiting heap-based objects in 'More Effective C++' by Scott Meyers.
http://www.informit.com/store/product.aspx?isbn=020163371X

Although that compiles I don't think it will run. This should cause a coredump or crash because it uses an uninitialized pointer

int main()
{
    A *a;
    a->create();
}

> This should cause a coredump or crash because it uses an uninitialized pointer
Yes, but normally a static method is called using the class name when it cannot be called on an object.

A *a = A::create();
commented: Great :) +28
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.