I am a bit confused by the const used in the declaration of the private function makeEmpty(). My understanding is that we put a constafter a member function, to indicate that this member function does not alter any of the data members. However, clearly this (private) makeEmpty function changes the variable root. Could someone help with this? Thank you quite a lot!
Also, a minor question is: in makeEmpty( BinaryNode * & t ), what is the point of using reference here? Can we just use the pointer?
1) Technically, it does not, since it only modifies root, which is pointed to by the pointer, but I do agree that it is kind of weird since that function could possible modify stuff if you pass parts of the class into the function. That function seems more like static function to me. Basically all the const does is make this into a const pointer to const data.
2) The reference is needed since you set t = NULL on the last line of the function. If you hadn't passed it by reference, then the original t that you had passed would not be modified.
makeEmpty( BinaryNode * & t ) doesn't modify the data in the object, it modifies the passed in data.
In this instance the passed in data happens to be a member variable. But that member variable is passed in by a non-const function makeEmpty( ).
So the caller called a non-const function which was able to obtain a modifiable reference to the member variable and cause it to be changed by passing it to the const function as *passed in data*. A const function would not have been able to pass in a modifiable reference to the internal data member root.
Thank you very much guys! It helps a lot. So can I understand it this way?
1. non-const makeEmpty( ) can change the member variable root, coz it's not a constfunction anyways.
2. Although makeEmpty( BinaryNode * & t ) const is not allowed to change root, it doesn't change root directly, but through being called by makeEmpty().
Also just want to make sure if it's correct: eventually root is still set to be NULL, right? This strange set-up is cited from a classical data structure book in C++ :-(
1) Yes. makeEmpty() can modify this, and thus can modify this->root.
2) makeEmpty(BinaryNode*&) is not allowed to modify this. However, it *is* allowed to modify what is passed to it (despite the fact that you *could* pass a pointer to some part of this)