0

In this code I'm not really sure what does keyword "const" is doing. My guess would be that it makes it not possible to change the private variables ​​of the class, but i'm not sure. Despite that I cannot understand the difference of "const" being ahead or behind the method. Or is it the same thing?

class Date
{
public:
    Date(unsigned int y, unsigned int m, unsigned int d);
    Date(string yearMonthDay); // yearMonthDay must be in format "yyyy/mm/dd"
    void setYear(unsigned int y);
    void setMonth(unsigned int m);
    void setDay(unsigned int d);
    void setDate(unsigned int y, unsigned int m, unsigned int d);
    unsigned int getYear() const;
    unsigned int getMonth() const;
    unsigned int getDay() const;
    string getDate() const; // returns the date in format "yyyy/mm/dd"
    void show() const; // shows the date on the screen in format "yyyy/mm/dd"
private:
    unsigned int year;
    unsigned int month;
    unsigned int day;
};

1 Answers1

0

Let's say you don't have a Date object at hands, but only a const reference to it, const Date&. You are only allowed to call const methods on that reference. These methods guarantee with their signature that they will not alter the Date object (and the compiler will also not allow it). An exception to this are mutable members.

A const keyword in front of the signature relates to the return argument. So for example, const std::string& getName() const; returns a const reference to a string. It is const itself, because it does not alter the object. These are the two meanings of const in front and end of the signature.

ypnos
  • 50,202
  • 14
  • 95
  • 141