A nice question, I came through while being in an interview. Well, so how do you make sure that the object can be instantiated only on heap and not on stack ? so, if you are of the kind who don’t think without being given the use and purpose .. well the purpose is that your class may be a heavy one so storing objects on stack may be a killer.
Answer popped up my mind quite easily. Let’s suppose we have a class A,
class A {
int a[10000];
public:
A();
void print_arr();
}
Use the C++ access specifiers and make the constructor itself private. Now there is no way to instantiate the class. Pretty useless.
class A {
int a[10000];
A();
public:
void print_arr();
}
Now let’s make it useful by adding a factory function (or method) to it. This will act as the only way to instantiate an object. As with any factory method, it has to be static to be actually useful. Otherwise its as dumb a class as the one above.
class A {
int a[10000];
A();
public:
static A* getAnObject() { return new A(); }
void print_arr();
}
well that was it. problem solved. I am such a happy go lucky. But my interviewer friend had yet another idea (probably) in his mind and he asked me for some other way.
I am still puzzled.. some one there for help ?
Filed under: C++, Programming