Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we need to put const at end of function header but static at first?

Tags:

c++

I have code like this...

class Time
{
    public: 
        Time(int, int, int);
        void set_hours(int);
        void set_minutes(int);
        void set_seconds(int);

        int get_hours() const;
        int get_minutes() const;
        int get_seconds() const;

        static void fun() ;

        void printu() const;
        void prints();

    private:
        int x;
        int hours;
        int minutes;
        int seconds;
        const int i;
};

Why do I need to put const at last to make a function constant type but if i need to make a function, I can do this like...

static void Time::fun() 
{
    cout<<"hello";
}

Above function fun() is also in same class. I just want to know what is the reason behind this?

like image 567
teacher Avatar asked Aug 30 '11 19:08

teacher


People also ask

Why do we use const at the end of a function header?

Putting const after a function declaration makes the function constant, meaning it cannot alter anything in the object that contains the function.

What does putting const at the end of a function mean?

const at the end of a function signature means that the function should assume the object of which it is a member is const . In practical terms it means that you ask the compiler to check that the member function does not change the object data in any way.

Why do we use const in functions?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.

What does const in front of a function mean?

const after member function indicates that data is a constant member function and in this member function no data members are modified.


1 Answers

with a const instance method such as int get_hours() const;, the const means that the definition of int get_hours() const; will not modify this.

with a static method such as static void fun();, const does not apply because this is not available.

you can access a static method from the class or instance because of its visibility. more specifically, you cannot call instance methods or access instance variables (e.g. x, hours) from the static method because there is not an instance.

class t_classname {
public:
  static void S() { this->x = 1; } // << error. this is not available in static method
  void s() { this->x = 1; } // << ok
  void t() const { this->x = 1; } // << error. cannot change state in const method
  static void U() { t_classname a; a.x = 1; } // << ok to create an instance and use it in a static method
  void v() const { S(); U(); } // << ok. static method is visible to this and does not mutate this.

private:
  int a;
};
like image 182
justin Avatar answered Sep 16 '22 13:09

justin