Interview Question: Heap vs. Stack

Sample Question #80 (programming – C++)

[Just heard this really good C++ concept question from my colleague, so wanted to put it down here]

How do you define a class so that only heap-based objects can be created from this class, but stack-based objects are not allowed?

[Courtesy of Zhaoyang Zhao of ITG]

Advertisements
This entry was posted in Sample Qs. Bookmark the permalink.

3 Responses to Interview Question: Heap vs. Stack

  1. Brett says:

    ANSWER
     
    First, you should know that heap-based objects use dynamic memory allocation. So this means you need the {class_name} *{object_name} = new {class_name} method. Second, to disallow the {class_name} {object_name} type of declaration, you need to make the class’ constructor private.
     
    (This is a hard question. If you got it right, treat yourself to a steak dinner!)

  2. Nathan says:

    not quite, a public constructor is required for both cases. to force heap creation you need to make the constructor private AND add a static method to create new objects (factory pattern). like this:
     

    #include <iostream>using namespace std;
    class heap_only{public:    void foo() const { cout << "heap_only" << endl; }    static heap_only* create() { return new heap_only(); }
    private:    heap_only() {}};
    class stack_only{public:    void foo() const { cout << "stack_only" << endl; }
    private:    void* operator new(size_t x);    void* operator new[](size_t x);};
    int main(int argc, char* argv[]){    stack_only so;    so.foo();
        // stack_only* pso = new stack_only(); // cannot access private member: stack_only::operator new    // stack_only* aso = new stack_only[10]; // cannot access private member: stack_only::operator new[]
        // heap_only ho; // cannot access private member: heap_only::heap_only    // ho.foo();
        heap_only* pho = heap_only::create();    pho->foo();    delete pho;
        return 0;} 

  3. Brett says:

    enigmagic, I think you’re right. Thanks for the correction as well as example. -brett 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s