Recently I have attended one C++ technical interview: during that interviewer asked me one question which I was not able to answer: Even I tried on internet and some forums however unable to get the answer, Please see the code snippet below:
using namespace std;
class Base1
{
public:
Base1()
{
cout << "Base1 constructor..." << endl;
}
~Base1()
{
cout << "Base1 Destructor..." << endl;
}
};
class Base2
{
public:
Base2()
{
cout << "Base2 constructor..." << endl;
}
~Base2()
{
cout << "Base2 Destructor..." << endl;
}
};
class Derived : public Base1, public Base2
{
public:
Derived()
{
cout << "Derived constructor...." << endl;
}
~Derived()
{
cout << "Derived Destructor..." << endl;
}
};
int main()
{
cout << "Hello World" << endl;
Base1 b1; Base2 b2;
Derived d1;
return 0;
}
Description: There are two base classes named Base1 and Base2 and one derived class named Derived. Derived is multiple inherited from Base1 and Base2.
The question:I want Derived should be inherited only from one class not from both. If developer will try to inherit from both classes: then the error should generate: let me summarize it:
- Scenerio 1: class Derived : public Base1 // Ok.---> No Error
- Scenerio 2: class Derived : public Base2 // Ok.---> No Error
- Scenerio 3: class Derived : public Base1, public Base2 // Error or exception or anything. Not able to inherit.
Note: Can you answer this problem: I am really not sure whether this is feasible or not. And one more thing: this is not a diamond problem.
Thanks.