I am studying tree exploration, I implemented a class "CNode" for the nodes where each node has a pointer member to point to his parent, my question is about a const function and a const member, see below in my code.
So below is a simplified version of the main and of the class.
class CNode
{
private:
int m_nID;
CNode* m_pParent;
public:
CNode() : m_nID(0), m_pParent(nullptr) {}
CNode(int n, CNode* pParent) : m_nID(n), m_pParent(pParent) {}
CNode* GetParent() const { return m_pParent; }
void PrintID() const { cout << m_nID << endl; }
CNode* CreateChild(int n)
{
CNode* pNode = new CNode(n, this);
return pNode;
}
};
int main()
{
CNode* pNodeRoot = new CNode(0, nullptr);
CNode* pNode = new CNode(1, pNodeRoot);
while (pNode != nullptr)
{
pNode->PrintID();
pNode = pNode->GetParent();
}
delete pNodeRoot;
delete pNode;
return 0;
}
So that is working but I am not satisfied because the member function:
CNode* CreateChild(int n)
should be const, so let's put it const but because it is using "this" then I have to put the member "m_pParent" const (which seems normal as in my case the node won't change parent), at the end it looks like that:
class CNode
{
private:
int m_nID;
const CNode* m_pParent;
public:
CNode() : m_nID(0), m_pParent(nullptr) {}
CNode(int n, CNode* pParent) : m_nID(n), m_pParent(pParent) {}
CNode* CreateChild(int n) const
{
CNode* pNode = new CNode(n, const_cast<CNode*>(this));
return pNode;
}
const CNode* GetParent() const { return m_pParent; }
void PrintID() const { cout << m_nID << endl; }
};
and then I have to change one line in the main using a const_cast:
pNode = const_cast<CNode*>(pNode->GetParent());
and it is working as well.
Both versions are working, I would like your advice to know:
- what is the best practice,
- if using const_cast is ok or not (I thought that was to avoid as much as possible),
- if there is another way (simpler or neater) to do it.
Thank you.