Microsoft Interview Question
abcsCountry: India
Interview Type: In-Person
I think they are looking for something like a singleton pattern...
#include <iostream>
class ABC {
private:
ABC() {
std::cout << "ABC";
}
~ABC() {
if (m_ABC != NULL)
delete m_ABC;
}
public:
static void fun() {
if (m_ABC == NULL) {
// create an instance of ABC
m_ABC = new ABC();
}
}
private:
static ABC *m_ABC = NULL;
};
int main() {
ABC::fun();
return 0;
}
Declare fun() as non static.
Then you can't make a call to fun() just by referring it via class name.
You have to call this function through object only instead of class like :-
ABC a; // statement 1
a.fun(); // statement 2
But as you the constructor is private and you can't make an instance, so
statement 1 would be illegal.
Also, still you could able to do it by using the below piece of code :-
ABC *a; // statement 1
a->fun(); // statement 2
As fun() is not making any reference to "this" object, so the above 2 statements were possible.
To overcome this, access some data from fun() as below :-
class A {
private:
int z;
A() { cout << " Constrcutor got called " << endl; }
~A() { cout << " destructor got called " << endl; }
public:
static void fun() { A aa; } // statement 1
void fun2() { A aa; } // Statement 2
void fun3() { z = 10; A aa; } // Statement 3
};
int main() {
A::fun();
A *a;
a->fun2();
a->fun3();
}
Now statement 3 will give segmentation fault and call to the constructor will be restricted in this way.
I'm a noob at this, but it looks like they want to see some form of a singleton pattern. Here's my stab at it.
- Brendan June 19, 2016