Bloomberg LP Interview Question
Software Engineer / Developersadd a explicit keyword before the class constructor. Then the constructor with single argument wouldn't go for implicit conversion.
@Manish
Explicit won't help you in this case. Also adding a explicit key word doesn't mean you won't be able to put the object on stack.
Explicit is helpful in a case of "Conversion constructor".
So calling constructor " A a(1) ;" doesn't make any difference with or without explicit .
but when " A a =1; " is used, adding explicit with constructor will not allow to create the object this way but you can still create the object on stack..
Create another class lock with private constructor.
Drive your class "A" with it.
class lock
{
private:
lock()
{}
};
class A: public lock
{
// Any constructor
};
This disables the instantiation of your class "A"
I think ashutosh is speaking with respect to Class A, where it will not allow to create object in stack..But either it will not allocate object through heap also.
How about this? Create another class (Foo) and have its no argument constructor private. Derive the given class A from the above create Foo class. However this will prevent any constructors of class A to work. I am not sure what the intent is.
class A
{
public:
A(int i)
{
}
private:
A() {}
~A() {}
public:
static A* instance()
{
return new A();
}
static void free_instance(A* a)
{
delete a;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
A a1(2); // error C2248: 'A::~A' : cannot access private member declared in class 'A'
A* aa = A::instance();
A::free_instance(aa);
}
Here is the solution
- Boris May 11, 2010class A
{
public:
A(int i)
{
}
private:
A() {}
~A() {}
public:
static A* instance()
{
return new A();
}
static void free_instance(A* a)
{
delete a;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
A a1(2); // error C2248: 'A::~A' : cannot access private member declared in class 'A'
A* aa = A::instance();
A::free_instance(aa);
}