-1

What is the difference between the various usages of the const keyword in the function header/prototype?

    const int function(const int x) const;

Answer:

The 1st const is to return by constant value shown here.

The 2nd const is to have a constant function parameter shown here.

The 3rd const is used when the function is a class method/function that should only perform some sort of query operation such as get, hence should not change any of the class attributes/data variables shown here.

MShakeG
  • 391
  • 7
  • 45

1 Answers1

5
const E& top() const throw(StackEmpty);

const E& is the return type of the function top(). It is a reference to a constant E.

The const after the name of the function specifies, that the function won't modify the instance it is called upon and thus can be called on const-qualified instanced of the struct/class, top() is a member of.

The throw()-specification tells, that top() may throw an object of type StackEmpty. AFAIK such throw()-specifications naming a specific type are depreciated since C++11.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • 1
    Sidebar: Some good reading on why throw specifications were removed from the language: http://www.gotw.ca/publications/mill22.htm – user4581301 Sep 08 '18 at 17:14