Why should I use virtual base classes?

According to what I read, a virtual base class is used when you have an abstract base class that contains data, so the class will not be replicated, but what is the problem with class replication if you are not using a virtual class

And should we abstract the base class that contains the data?

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 "C ++ Programming Language" 4th edition - Bjarn Stroustrup.

+4
source share
2 answers

, Storable, Radio , Transmitter Receiver.

, Radio Storable, , , , , ( , ).
, Storable ( ), ? Storable, Transmitter Storable, Receiver

, Storable, .

: ++, ?

+5

, "" , , .. DIAMOND PROBLEM. , , "::", , , . ,

+2

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


All Articles