0

Below Code is on Diamond problem. virtual inheritance solves this ambiguity.

    #include<iostream>
    using namespace std;

    class A {
    public: void something(){cout<<"A"<<endl;} 
    };

    class B: virtual public A
    {
    public: void something() {cout<<"B"<<endl;} 
    };

    class C: virtual public A {
    public: void something() {cout<<"C"<<endl;} 
    };

    class D: public B, public C {
    public: void something() {cout<<"D"<<endl;} 
    };

    int main()
    {
        A *d = new D();
        d->something();
    }
  1. How virtual inheritance solves this problem?? will it have vtable entry?
  2. Which path is taken by the compiler to reach parent class??
curiousguy
  • 8,038
  • 2
  • 40
  • 58
Vijay M M
  • 81
  • 6
  • 1
    You may want to give this nice resource a read: https://isocpp.org/wiki/faq/multiple-inheritance – NathanOliver Jun 07 '16 at 14:18
  • virtual inheritance has nothing to do with virtual functions and vtable. – SergeyA Jun 07 '16 at 14:18
  • 2
    Possible duplicate of [How does virtual inheritance solve the diamond problem?](http://stackoverflow.com/questions/2659116/how-does-virtual-inheritance-solve-the-diamond-problem) – PcAF Jun 07 '16 at 14:18
  • 1
    @SergeyA - that is wrong. In C++ virtual inheritance is implemented by changes in the semantics of the vtable – Smeeheey Jun 07 '16 at 14:26
  • @Smeeheey, show me a single mentioning of vtable in C++ standard, and your argument will have merits. – SergeyA Jun 07 '16 at 14:38
  • 1
    The vtable is an implementation detail, and the standard does not specify implementation, so you're right it does not mention it. However you said "virtual inheritance has nothing to do with virtual functions and vtable" - this is what I disagree with. – Smeeheey Jun 07 '16 at 14:41
  • @SergeyA Because vtable aren't part of the semantics of C++, but a tool used by every known compiler to implement C++, using the std to support arguments about vtable wouldn't make sense. – curiousguy Jun 23 '16 at 17:28
  • @Smeeheey "_In C++ virtual inheritance is implemented by changes in the semantics of the vtable_" Not all compilers create vtables for classes with no virtual functions. The code in the question has no virtual functions. – curiousguy Jun 23 '16 at 17:29
  • "_virtual inheritance has nothing to do with virtual functions_" virtual inheritance has everything to do with virtual functions – curiousguy Jun 23 '16 at 17:31
  • "_Which path is taken by the compiler to reach parent class??_" I am not sure I understand your question, why do you need to know? – curiousguy Jun 23 '16 at 17:33
  • I was curious to know how parent class method is called via class B or via class C – Vijay M M Jun 23 '16 at 17:46

1 Answers1

1

When using virtual inheritance, the parent class's members are shared between all the child classes, rather than being duplicated for each child class so actually there is no diamond.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154