0

I know compiler gives error for ambiguity if we don't mention virtual keyword while deriving child class in diamond problem. So how virtual keyword removes this ambiguity?

DevMJ
  • 2,810
  • 1
  • 11
  • 16

1 Answers1

0

From isocpp faq

class Base {
public:
  // ...
protected:
  int data_;
};
class Der1 : public virtual Base {
                    ↑↑↑↑↑↑↑ // This is the key
public:
  // ...
};
class Der2 : public virtual Base {
                    ↑↑↑↑↑↑↑ // This is the key
public:
  // ...
};
class Join : public Der1, public Der2 {
public:
  void method()
  {
     data_ = 1;  // Good: this is now unambiguous
  }
};
int main()
{
  Join* j = new Join();
  Base* b = j;   // Good: this is now unambiguous
}

if you didn't specify the inheritance as virtual, the compiler would try to add two Base classes in the Derived object, and it wouldn't know which data_ to fill in. You would effectively have two objects that are the same in your derived class. Declaring the inheritance as virtual tells the compiler that you want only one instance of the base class in the derived class.

dau_sama
  • 4,247
  • 2
  • 23
  • 30
  • Thanks dau_sama. In this case size of Join class is 12 which include 2 virtual pointer of Der1, Der2 and 4bytes of data_(I think). Is it correct? Also which path is used by the compiler to maintain single copy of Base object? – DevMJ Aug 16 '16 at 05:02
  • I think that's correct in gcc/x86, but it is implementation defined. Probably on other architectures it might be implemented in a different way. In this simple case the compiler simply knows that it only has to reserve one instance the base object in the memory layout. – dau_sama Aug 16 '16 at 05:12