2

Like this,

bool isEmpty() const { return root==NULL; }

This is isEmpty function, test if the BST is empty or not.

1

4 Answers 4

11

It indicates that the function does not modify any of the members of that class.

Usually, the Interface/declaration(through header file) is made available to the users of the class/functions and not the implementation,So the const makes it clear to the user that the function does not modify any members.

Adding the const also makes the user of the function aware that this const member functions should be used when you have an const object.You cannot call normal member function on a const object of that class,it will result in a compiler error.

That is the reason that the function is marked const even if it is empty.It indicates a contract between the function implementer and the user of the function.

Sign up to request clarification or add additional context in comments.

4 Comments

Also that it is callable if you have a const version of the object. Non const functions are not callable from a const instance.
@Als you are saying 'const member functions can only be called on a const object of that class'. That is not true: const member functions can be invoked on non-const objects too :) The other way around however is not possible
@TomKnapen: Ah,Ofcourse,English can play tricks sometimes(especially to non native English speakers like me) :). Thanks I corrected that typo.
If you have a const version of an object and you are calling a method of that object, then if the compiler complains that there is no such function, it is because that method is not const.
2

When a function is marked as const, the function can be invoked on a const instance of the class. Invoking a non-const function on a const object will lead to a compile-time error.

Basically, you want to mark all functions that don't change the state of your object as const; this way, you can use const as an immutability declaration and the compiler will enforce it for you, by making sure you can only invoke the const functions.

You can invoke const functions on a non-const instance no problem.

Comments

0

It tells the compiler that the function will not modify the state of the class. Also, const functions are the only functions allowed to be called on const objects.

Comments

0

It indicates that the function is logically constant, that is, as far as users of the class are concerned, the value of the class member is not changed by the function. It is legal to call const functions on const references and through const pointers.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.