Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent multiple inheritance in C++ [duplicate]

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.

like image 710
hims Avatar asked Dec 19 '13 08:12

hims


1 Answers

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:

  • error C2555: 'D::a': overriding virtual function return type differs and is not covariant from 'B1::a'
  • see declaration of 'B1::a'
like image 119
egur Avatar answered Oct 05 '22 23:10

egur