1

What is the difference between

class A {};
class Z: public A {};

and

class A {};
class Z: virtual public A {};
Evg
  • 25,259
  • 5
  • 41
  • 83
MGE
  • 872
  • 1
  • 8
  • 14
  • You may take a look at the "diamond problem". See [this question](http://stackoverflow.com/questions/2659116/how-does-virtual-inheritance-solve-the-diamond-problem). – zakinster Sep 13 '13 at 13:50

3 Answers3

9

Assuming that there is no additional inheritance hierarchy, there is no difference in this case. The only way to see a difference is inheriting the same class through multiple ways - for example, as follows:

class ZA : public Z, public A {};

vs.

class ZA : virtual public Z, virtual public A {};

In the first case, ZA would have two regions with separate As - one inherited directly, and one inherited through Z. In the second case, there would be only one A, inherited through both paths, and shared.

Here is an illustration of this:

Virtual vs. Regular inheritance

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 2
    Ok.. so... What's the difference?? – MGE Sep 13 '13 at 13:51
  • `Assuming that there is no additional inheritance hierarchy, there is no difference in this case.` This is not true. In the first case, `sizeof(Z)` is typically one. But in the second case, `sizeof(Z)` is typically `sizeof(void*)` because `Z` will contain a vtable pointer even if `A` and `Z` do not contain virtual member functions. – Evg Jun 29 '20 at 19:52
3

The difference is in the behaviour when you inherit from multiple classes which share a common base class:

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

In this case, with non-virtual inheritance, a YZ object would contain Y and Z subobjects, each with their own A subobject.

This is usually not what you want, as it doesn't follow the "is-a" relationship that inheritance usually models: there are two different ways in which a YZ can be viewed as an A.

void f(A&);
YZ yz;
f(yz);    // ERROR: which A?

But with virtual inheritance of A, there will be only one A subobject, shared by the Y and Z; the example above will now be unambiguous.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

Suppose you have two derived classes B and C that have a common base class A. And you have another class D that inherits both of them. You would use public virtual A to ensure that both B and C use the same subobject A.

Info taken from here: Virtual Base Classes

Tyler Jandreau
  • 4,245
  • 1
  • 22
  • 47