I want to access class InternalNode’s getSurplus() method.
I have getSurplus() defined in a “InternalNode.h” file.
“…” means other code.
How do I refer to the method getSurplus from the InternalNode class?
//InternalNode.h
{
class InternalNode:public BTreeNode
{
...
void remove(int a);
int getSurplus() const;
...
}
}
int InternalNode::getSurplus() const
{
return (count - (internalSize + 1) / 2);
}
//
BTreeNode* InternalNode::remove(int value)
{
...
if (children[i]->getSurplus() >= 0) return SURPLUS; //Not correct syntax
...
}
Since
childrenis an array ofBtreeNode*objects, andInternalNodeis derived fromBtreeNode, then provided that the pointer returned fromchildren[i]is in-fact a pointer to aInternalNodeobject (and not some other derived object ofBtreeNode), you have to explicitly cast the pointer back to a typeInternalNode*. This could be done like so:If you are not sure that each
BtreeNode*is pointing to anInternalNodeobject (i.e., it could be pointing to some other derived type), then you’re going to have to use adynamic_cast<InternalNode*>(children[i]), and check to make sure the operation returns a valid pointer, and notNULL.So if you’re absolutely sure about the types in your array, then you can use
static_cast<>()in this situation (i.e., right nowBtreeNodeis the only base-class ofInternalNode, it is not a virtual base class, etc.) … otherwise if you want to be safe at the cost of some run-time overhead, usedynamic_cast<>()and check for aNULLpointer return value from the cast operation.