Are we facing a situation of Dangling Pointer here? Why and how? Please explain.
It depends on the implementation of Student. If Student looks like this ...
class Student
{
public:
char* m_name;
Student(const char* name)
{
m_name = new char[strlen(name)+1];
strcpy(m_name,name);
}
~Student()
{
delete[] m_name;
}
};
... then there's a problem: when you copy a Student then you have two pointers to the same m_name data, and when the two Student instances are deleted then the m_name data is deleted twice, which is illegal. To avoid that problem, Student need an explicit copy constructor, so that a copied Student has a pointer to different m_name data.
Alternatively if Student looks like this ...
class Student
{
public:
std::string m_name;
Student(const char* name)
: m_name(name)
{
}
};
... then there's no problem because the magic (i.e. an explicit copy constructor) is implemented inside the std::string class.
In summary, you need an explicit copy constructor (or explicitly no copy constructor, but in either case not just the default constructor) if the class contains a pointer which it allocates and deletes.