Hello, you need to write a program warehouse. For example, there are CDs and DVDs. Regardless of the type of disc, its contents can be: music, video, software.

Is it necessary to create two classes or is it possible to do it differently?

class CD { public: enum Type { music, video, PO }; }; class DVD { public: enum Type { music, video, PO }; }; 
  • better one class. If all parameters are the same. Disc type make a separate class and that's it - Saidolim

4 answers 4

Classes write when it is necessary to encapsulate (select in a separate place) some kind of behavior. Classes in programming are primarily code with methods that do something, and not just a display of entities from the subject area.

Therefore, if CD and DVD discs have the same behavior, then they need one class, possibly with different field values.

 enum class Content { Music, Video, /* ... */ }; class OpticalDisk { public: enum Kind { CD, DVD, BD }; ??? private: Kind kind_; Content content_; }; 

But it is possible that the classes of CDs and DVDs do not have any behavior at all. Then do not make them classes, make the usual data structure

 struct OpticalDisk { enum Kind { CD, DVD, BD }; Kind kind; Content content; }; 
  • Is there any difference in the presentation of data between class and structure?) - Arkady
  • @Arkady is not - Abyx
  • one
    Plus The approach, when Data and Control are separated, as experience shows, is almost always a winning one. You do not know how better - scatter. The data in the struct is managed in a separate class with methods. - Arkady
  • The Content type is also enumerated (music, video, software), is it possible to create enum Content {music, video, PO}; ? - Andrei P.
  • @ AndreiP., Yes, it was meant, added in response - Abyx

You can use the composition

 class Types { public: enum DataTypes {music, video, PO}; enum DiskTypes {CD, DVD}; DataTypes DataType; DiskTypes DiskType; } class Disk { public: Types Type; } 

    It is possible to push a kind of a disk as in transfer, thus it is possible to create one class.

      Alternatively, you can muddle two parallel class hierarchies: a data carrier (media) and a data type (data):

       class Data { public: virtual ~Data() {} }; class Media { Data* data; public: Media(Data* d) : data(d) {} virtual ~Media() {} }; class Music : public Data { }; class Video : public Data { }; class DVD : public Media { using Media::Media; }; class CD : public Media { using Media::Media; }; int main() { Media* m = new DVD(new Video); }