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:
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.
Declare a pure virtual function in both bases that have a different return type:
class B1 {
virtual void a() = 0;
};
class B2 {
virtual int a() = 0; // note the different return type
};
It's impossible to inherit from both.
class D : public B1, public B2 {
public:
// virtual void a() {} // can't implement void a() when int a() is declared and vice versa
virtual int a() {}
};
int main(void) {
D d; // produces C2555 error
return 0;
}
This error is produced:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With