Bogdan Maier
Bogdan Maier

Reputation: 683

Why does "const" get used in this example?

Hello I'm wondering why is const used at the "get" functions in this class?

class Album {

public:
    Album(string c, Artist* a, string t, int y, int no):barCode(c), artist(a), title(t), year(y), noCopiesSold(no){}
    const string& getBarCode() const {return barCode;}
    Artist* getArtist() const {return artist;}
    const string& getTitle() const {return title;}
    int getYear() const {return year;}
    int getNoCopiesSold() const {return noCopiesSold;}
    void setBarCode(string value) {barCode = value;}
    void setArtist(Artist* value) {artist = value;}
    void setTitle(string value) {title = value;}
    void setYear(int value) {year = value;}
    void setNoCopiesSold(int value) {noCopiesSold = value;}

    friend ostream& operator << (ostream& out, const Album& album)
    {
        out << album.artist->getName() << " " << album.barCode << " " << album.title << " " << album.year << " " << album.noCopiesSold << endl;
        return out;
    }

private:
    string barCode;
    Artist* artist;
    string title;
    int year;
    int noCopiesSold;
};

Upvotes: 0

Views: 151

Answers (3)

Steve Townsend
Steve Townsend

Reputation: 54128

Aside from the function qualifiers - for the string getters (barcode, title), you are returning a const reference to a data member - allowing the referenced value to be mutated would break encapsulation in the class.

For this reason, returning Artist* is bad (or at best suspect) design.

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 59987

const tells the compiler that the method does not change the object. This means that it is safe to operate on const objects (as well as non-const objects). It also enables the compiler to make some optimizations

Upvotes: 3

iammilind
iammilind

Reputation: 69958

why is "const used at the "get" functions in this class?

For const-correctness.

  1. By making a function const, it implies that the function is not changing any non-static member variable inside it and no other non-const function is called inside this method
  2. The function now can be called using a const object also (otherwise results in compiler error)
  3. Many library functions make use of const correct methods; so const-correctness make your method compatible with it (e.g. less than operator -- bool <Class>::operator < (const Class&) const)

Upvotes: 3

Related Questions