Goldman Sachs Interview Question
Developer Program EngineersIt can be done as follows:
class A
{
private:
A(){}
public:
static A* createObject(){return new A();}
};
main()
{
A* a=A::createObject();
}
This way the class is stopped from being inherited and still can be instantiated.
@prashant
He made the constructor of the class private. Now if any of the child class try to create an object of the base class they will not be able to do it. For the second condition (i.e we should be able to make an object of base class) he made a static function which is creating an object of the base class.
Thus both the conditions are fulfilled.
Define a class with private constructors and a friend class.
Define the friend class inherited from the previous class.
Now this friend class can not be inherited but its objects can be created.
We can call constructor via its objects because it is a friend class object but
inherited class objects can not call the constructor so no inheritance possible.
#include<iostream>
using namespace std;
class A
{
public:
static A ACons();
protected:
private:
A();
};
A::A()
{
cout<<"In A constrcutor"<<endl;
}
A A::ACons()
{
new A();
}
class B
{
public:
B();
private:
};
B::B()
{
cout<<"In B constrcutor"<<endl;
}
int main()
{
A a=A::ACons();
cout<<"Address of A is"<<&a<<endl;
// A b=new (A::ACons());
getchar();
return 0;
}
As I understand we need to make a final class(As in Java), whose object we can create , but cann't be inherited.THis can be achive using virtual inheritence .here the code
// Final class
class final;
class dummy_class
{
friend class final;
private:
dummy_class(){};
};
class final :virtual public dummy_class
{
};
int main()
{
final f;
return 1;
}
So in above code we are able to create a object of final
now try to inherit it
// Final class
class final;
class dummy_class
{
friend class final;
private:
dummy_class(){};
};
class final :virtual public dummy_class
{
};
class error_class:public final
{
};
int main()
{
final f;
error_class e;
return 1;
}
So when u create a object of inherit class it will throw an error.
If constructor is private, then also can inherit it using public specifier. So DK is correct to make the constructor private.
class Base
{
private:
Base();
friend class Final;
};
//Since Final is friend of Base, it can access private Constructor.
//So it can be created on stack.
class Final : public Base
{
public:
Final();
};
class Child : public Final
{
public:
Child(); // You can't do this since it Child don't have access to Base constructor
}
Nice tricks!
Would you pls explain why it's not possible to inherit B in your given example? Thanks in advance.
Actally in c++ the default type is private.so here the access specifier of baseclass is not specified in derived class while inheriting the baseclass. so by default it is private and so the members of all the base class will not accessible by derived class B........
make the class final
- deepak November 10, 2011