Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Should I use virtual base classes?

According what I read, virtual base class is used when you have a abstract base class that holds data, so the class wont be replicated, but, what is the problem with replicate the class, if you don't use virtual class?

And should abstract base class that holds data be avoided?

follows an example:

class Storable {
public:
  Storable(const string& s);
  virtual void read() = 0;
  virtual void write() = 0;
  virtual ~Storable();
protected:
  string file_name; // store in file named s
  Storable(const Storable&) = delete;
  Storable& operator=(const Storable&) = delete;
};

class Transmitter : public virtual Storable {
public:
  void write() override;
  // ...
};

class Receiver : public virtual Storable {
public:
  void write() override;
 // ...
};

class Radio : public Transmitter, public Receiver {
public:
  void write() override;
  // ...
};

This example was taken from the book The C + + Programming Language 4th Edition - Bjarne Stroustrup.

like image 463
Alex Avatar asked Mar 20 '23 13:03

Alex


1 Answers

To keep it short, if you wouldn't use virtual inheritance for Storable then Radio would inherit it twice, once from Transmitter and once from Receiver.

That means that Radio needs memory for 2 instances of Storable which is some memory overhead and you'd most likely want both to have identical data anyways (If you don't inherit it virtually you'd have to manually manage that).
Also when you call a base class function from Storable (or access a data member), which one do you want to call? The one from Storable that got inherited through Transmitter or the one from the Storable that got inherited through Receiver

Virtual inheritance takes care of that with only having a single instance of the Storable base class that all the inherited classes share.

For mor information on virtual base classes, there's a nice question here: In C++, what is a virtual base class?

like image 142
AliciaBytes Avatar answered Mar 23 '23 02:03

AliciaBytes