Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

side effects of virtual public class in C++

Tags:

c++

class

virtual

Virtual Public Class is used for a class to ensure that an object of a class 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

Do we have side effect when we use virtual public when we don't use it for single inheritance. For example, is

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

the same as

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

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

like image 475
prosseek Avatar asked Dec 29 '22 00:12

prosseek


2 Answers

It's just as safe to make the parent class virtual "just in case." The standard doesn't specify how virtual inheritance will be implemented, but there will probably be a slight performance hit. Unless you're writing something performance-critical, you shouldn't need to worry about it.

like image 124
user253751 Avatar answered Jan 12 '23 23:01

user253751


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

classes needed to be extended with one or more virtual pointers, and a simple attribute lookup in an object now needs two indirections through the virtual table

Not unlike virtual functions.

like image 43
Shreesh Avatar answered Jan 12 '23 23:01

Shreesh