Detailed analysis of the process of virtual inheritance to solve the ambiguity problem caused by diamond inheritance

 二义性问题请详细看:

http://blog.csdn.net/lxp_mujinhuakai/article/details/69414277 To
solve the problem of the previous article, look at the following code:

#include<iostream>
using namespace std;

class Grandam
{
public:
     void introduce_self()
    {
        cout << "I am grandam." << endl;
    }
};

class Mother :virtual public Grandam
{
public:
    void introduce_self()
    {
        cout << "I am mother." << endl;
    }
};

class Aunt :virtual public Grandam
{
public:
    void introduce_self()
    {
        cout << "I am aunt." << endl;
    }
};

class Daughter :public Mother,public Aunt
{
public:
    void introduce_self()
    {
        cout << "I am daughter." << endl;
    }
};

int main()
{
    Grandam* ptr;
    Daughter d;
    ptr = &d;
    ptr->introduce_self();
    return 0;
}

The result is shown in the figure below:

Write picture description here
We can check the memory of the object to know the specific number stored in the memory:

, Break the point at ptr=&d, when the program runs to this point, print &d in the memory window, so that you can view the memory of object d * , as shown in the figure:*
Write picture description here

An address is stored in the first address of the memory. We enter this address 0x00eadc98 in the memory and check again what is stored in this address, as shown in the figure:

Write picture description here

It can be seen that the first row of the first two rows stores the offset of the base class object based on the base class, which is 0. The second line stores the offset 8 of the derived class object d based on the base class. The following summarizes the specific implementation process of virtual inheritance.


How does the object know which member is called? The specific process is as follows:
1. The pointer or reference knows which object you called;
2. The object can get the address that stores the offset based on the base class;
3. Get the base class based on the address offset;
4 whereby this base class object pointer plus the offset, then the call can distinguish which members of the derived class to which object.

Note:
1. After adding the keyword virtual, 4 more bytes will be allocated for the derived class object to store the address based on the offset of the base class (that appears in step 2).
2. After adding the keyword virtual, the inherited size of the diamond is only 4 bytes, instead of 8. Because the members of the base class only open up a space.
3. To solve the ambiguity problem, the keyword virtual must be added before the inheritance method of the position when the two derived classes inherit the base class for the first time.

Guess you like

Origin blog.csdn.net/lxp_mujinhuakai/article/details/69427582