Const and data hiding


In C++ when a member function returns a pointer which points to it’s member variable, there exists a possibility of the pointer address or the pointer value getting modified. This problem can be overcome by using the const keyword. An example illustrating this idea is given below

class Person
{
public:
Person(char* szNewName)
{
// make a copy of the string
m_szName = _strdup(szNewName);
};
~Person() { delete[] m_szName; };
const char* const GetName() const
{
return m_szName;
};
private:
char* m_szName;
};

In the above class the GetName() member function returns a pointer to the member variable m szName. To prevent this member variable from getting accidently modified the GetName() has been prototyped to return a constant pointer pointing to a constant value. Also the const keyword at the end of the function prototype states that the function does not modify any of the
member variables.

No comments:

Post a Comment