Yesterday I saw a question that was asking to prevent creating objects on heap.

After some thoughts, I came out the following:

class Foo
    Foo(const Foo& f) {}
    static Foo getAnInstance()
        return Foo();
    Foo() {}

But this can only guarantee the first object is on stack and it can’t go further because there is a public copy ctor.

I haven't seen the point of the question, but it's fun to think about; so my question: Is there a way to do so?

methods of a class are never ever on the stack -- only data objects go there.

int main()
    Foo f; // object f goes on the stack, but not the methods of that object.

Thank you, Dragon. Does that mean that, on our side (not the client side), to restrict the location of object creation is pointless? I mean that it's client's responsibility to determine where his/her objects should be located.

Thank you, vijayan121. I am going to take a look at the item.

I've gotten the point and solution :)
Thank you guys!

This question has already been answered. Start a new discussion instead.