Side effects of a virtual public class in C ++

A virtual public class is used for the class to ensure that the class object inherits only one subobject.

class L { /* ... */ }; // indirect base class class B1 : virtual public L { /* ... */ }; class B2 : virtual public L { /* ... */ }; class D : public B1, public B2 { /* ... */ }; // valid 

We have a side effect when we use virtual publishing, when we do not use it for single inheritance. For instance,

 class L { /* ... */ }; // indirect base class class B1 : virtual public L { /* ... */ }; class D : public B1 { /* ... */ }; // valid 

same as

 class L { /* ... */ }; // indirect base class class B1 : public L { /* ... */ }; class D : public B1 { /* ... */ }; // valid 

? I mean, is it possible to just make the parent class virtual for all possible cases?

+4
source share
2 answers

It is also safe to make the parent class virtual "just in case." The standard does not specify how virtual inheritance will be implemented, but there will likely be a slight decrease in performance. If you are not writing something critical, you need not worry about it.

+7
source

http://www.phpcompiler.org/articles/virtualinheritance.html

which should be expanded with one or more virtual pointers, and a simple search for attributes in the object now requires two indirectness through the virtual table

Unlike virtual functions.

+3
source

Source: https://habr.com/ru/post/1342934/


All Articles