Const keyword

Hi,

Some times why we use const keyword at last, Like as:

Fraction operator+( const Fraction &second ) const;
You forgot to ask a question.

I will assume you meant to ask "Why?" or "What does it mean?"

Keep in mind that you can declare a variable as constant in two ways:
1
2
const int x = 0;
int const y = 0;
I personally prefer the second form, because it is consistent with the use on member functions as you discovered. However, the first form is heavily used.

When you see const after a member function argument list, that means the member function cannot change the state of the object it is being invoked on - the compiler will enforce it by refusing to compile code that breaks this promise.
1
2
3
4
5
6
7
8
9
10
11
12
struct Example
{
    int x;
    void f()
    {
        x = 0; //fine
    }
    void g() const
    {
        x = 0; //error
    }
};
Last edited on
It means in this function

void g() const
{
x = 0; //error
}

we can't initialize variables, initialized first ? Am Right ?
No. It has nothing to do with initialization.
void g() const When you create member function, aside from arguments you provided, there is another hidden argument: pointer to the object you are working with. That trailing const (and/or volatile or ref-qualifier &/&&) relates to that hidden argument. Compare:
1
2
3
4
5
6
7
8
struct foo
{
    void bar() const;
};
bar(const foo&);
//...
f.bar();
bar(f);
Topic archived. No new replies allowed.