You get a bonus - 1 coin for daily activity. Now you have 1 coin

2.7. Multiple inheritance

Lecture



2.7.  Multiple inheritance

2.7.  Multiple inheritance

A class can have several immediate base classes.

class A1 {. . .};

class A2 {. . .};

class A3 {. . .};

class B: public A1, public A2, public A3 {. . .};

Such inheritance is called plural . With multiple inheritance, no class can be used more than once as a direct base. However, a class may be more than once an indirect base class.

class X {. . . f (); . . .};

class Y: public X {. . .};

class Z: public X {. . .};

class A: public Y, public Z {. . .};

We have the following hierarchy of classes (and objects):

2.7.  Multiple inheritance

Such a duplication of a class corresponds to the inclusion in the derived object of several objects of the base class. In this example, there are two objects of class X. To eliminate possible ambiguities, you need to contact a specific component of class X using the full qualification

Y:: X:: f () or Z:: X:: f)

Example.

2.7.  Multiple inheritance
To eliminate duplication of objects of an indirect base class in case of multiple inheritance, this base class is declared virtual .

2.7.  Multiple inheritance

Now class A will include only one instance of X, access to which classes Y and Z have equal rights.

2.7.  Multiple inheritance

Example 2.7.1

2.7.  Multiple inheritance

Here

· The base class object occupies 13 bytes in memory:

2 bytes - int field;

1 byte - char field;

10 bytes - field char [10].

· An object of class abase occupies 23 bytes in memory:

8 bytes - field double;

13 bytes - base base class fields;

2 bytes - for communication in the hierarchy of virtual classes;

· An object of class bbase occupies 19 bytes in memory:

4 bytes - field float;

13 bytes - base base class fields;

2 bytes for communication in the hierarchy of virtual classes;

· An object of class top occupies 33 bytes in memory:

4 bytes long field;

10 bytes - data and communications abase;

6 byte data and bbase communications;

13 bytes - fields of base class base.

If during base inheritance in the abase and bbase classes the base class is made non-virtual, the results will be as follows:

an object of class base takes up 13 bytes in memory;

an object of class abase occupies 21 bytes in memory (there are no 2 bytes for communication);

bbase class object occupies 17 bytes in memory (there are no 2 bytes for communication);

a top object occupies 42 bytes in memory (the base object enters twice).


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

C ++ (C plus plus)

Terms: C ++ (C plus plus)