evenafter learning functions , i see a lot new things everyday in functions. its great because it gives the opportunity to learn new things.

today , i see a function which have const keyword with function , like this :

void fun_name() const{


}

i couldn't understand it . would you guys please explain it ?

Recommended Answers

All 2 Replies

On class functions, it is a promise that this function will not change any member variables of the object.

There is an exception, and here is the next keyword for you; mutable. When a class member is declared mutable, it can be changed by a function with const on.

The following example code shows these, and has one function that will not compile as it tries to break the const

class example{

  int x;
  mutable int y;

  void change_x();
  void change_x_again() const;
  void change_y() const;
};

// This is fine
void example::change_x()
{
x++;
}


// This is NOT fine - it says it is const, but it tries to change the class object. 
// This should not compile
void example::change_x_again() const
{
x++;
}

// This isfine - it says it is const, but the variable it changes is mutable, so can be changed
void example::change_y() const
{
y++;
}

thanks
very nice explanation .
i got it even though i am not familiar with class concept .

i'll start learning on class concept next week.
once again thanks for your very nice explanation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.