Search code examples
c++encapsulation

What is the proper encapsulation syntax?


I have publication and library two classes and in publication class. How to manipulate(as encapsulation) genre, media, and target_age, If I want them to be separate classes. It's not class inside another class. The genre have more type's as (fiction, non-fiction, self-help, performance) as well as media and age. I have done my research I'm serchin for the proper syntax for it.

class Publication {    
  private:
    string title;
    string authore;
    string copyright;
    Genre genre;
    Media media;
    Age target_age;
    string isbn;
    bool checked_out;
    string patron_name;
    string patron_phone;

  public:
    void check_out(string patron_name, string patron_phone ){}
    void check_in(){}
    bool is_checked_out(){}
    string to_string(){}
};

Solution

  • The best way to encapsulate is to keep everything private. Create constant getters for stuff that might be read from the outside, and initialize everything in the constructor. After all, things like author/title/etc. should not ever change for an instance of a real book right? Have a look at the following snippet:

    class Publication {    
      private:
        string _title;
        string _author;
        Genre _genre;
    
      public:
        void check_out(string patron_name, string patron_phone );
        void check_in();
        bool is_checked_out() const;
    
        string to_string() const;
        string get_title() const { return _title; }
        string get_author() const { return _author; }
        const Genre& get_genre() const { return _genre; }
    
    
        Publication(string author, string title, Genre genre) : _author(auth), _title(title), _genre(genre)
        { }
    };