-
Const qualifier problem
This is a constructor for a binary tree that creates a copy of the tree given as argument....
Code:
Tree(const Tree<T>& aTree){
this->ghost = new Node<T>();
if(aTree.treeIsEmpty()){
this->root = this->ghost;
}else{
this->root = new Node<T>(aTree.getRoot()->key, 0, this->ghost, this->ghost);
this->treeCopyFill(aTree, aTree.getRoot(), this->root);
}
}
and its subroutine treeCopyFill...
Code:
void treeCopyFill(const Tree<T>& aTree, Node<T> * theOriginalFatherNode, Node<T> * theCopyFatherNode){
if(!aTree.isLeef(theOriginalFatherNode->left)){
theCopyFatherNode->left = new Node<T>(theOriginalFatherNode->left->key, theCopyFatherNode, this->ghost, this->ghost);
treeCopyFill(aTree, theOriginalFatherNode->left, theCopyFatherNode->left);
}
if(!aTree.isLeef(theOriginalFatherNode->right)){
theCopyFatherNode->right = new Node<T>(theOriginalFatherNode->right->key, theCopyFatherNode, this->ghost, this->ghost);
treeCopyFill(aTree, theOriginalFatherNode->right, theCopyFatherNode->right);
}
}
When I compile with GCC, I get the following error about 5 times....
passing const Tree<T> as 'this' argument of return_type Tree<T>::method [with T=int] discards qualifier
Can anyone explain what's happening and what can I do to solve the problem?
-
Indent your code better and use the [CODE] tag (the # button)
You should also compile with G++ not GCC though that is probably not the cause of your error
-
Ok done, now, can you help me?
-
You have a const "Tree" variable somewhere that you call a function on. However, there is no const version of the function. Const versions are declared by adding "const" at the end, like so:
Code:
void Class:funcName() const;
It informs the compiler the function is allowed to be called even if the object it is called on is const. It also informs the compiler that the "this" object will NOT be modified in this function.
-
Thanks mate! I'll try it right away!
-
It works thanks!
I've had a lot of trouble with tose things in the past and always had to find another way to do what I wanted. Not only your answer was very helpful this time but since I can understand it clearly I'll be able to use it again in the future!