C++ - Destructor
Destructors are also the special type of functions provided in C++ and they will get called jyst before the object gets deallocated.
Remember that a class can have only one destructor where as they can be many construcors. tMyClass is the class name in the example and the destructor is defined in as ~MyString(), is nothing but the class name.
Remember the following points in Destructors
- There is a virtual destructor. so you can declare destructor as virtual.
- Desstructor can not return any value.
- If you have to return any value from desstructor, then use the exceptions.
- Destructors are usually called automatically at the time of object destruction. There might be very rare cases, you may need to call explicitly, but is not an usual practice.
- Destructor can be declared private, protected or public to restrict the access level. You can ask one questions - What is the need for declaring constructor as private? Refer to singleton class for more details.
- There can be any number of constructors but only one destructor
Source Code
class MyString
{
private:
char *m_pString;
public:
MyString()
{
std::cout << "Calling Default Constructor\n";
m_pString = NULL;
}
~MyString()
{
if( this->m_pString != NULL)
{
std::cout << "Calling Destructor\n";
delete this->m_pString;
this->m_pString = NULL;
}
}
MyString(const char *p)
{
std::cout << "Calling Parameterized Constructor\n";
int len = strlen(p);
m_pString = new char [len + 1];
strcpy(m_pString, p);
}
MyString(const MyString &other)
{
std::cout << "Calling Copy Constructor\n";
m_pString = other.m_pString;
//int len = strlen(other.m_pString);
//m_pString = new char [len + 1];
//strcpy(m_pString, other.m_pString);
}
const MyString& operator = (const MyString &other)
{
std::cout << "Calling assignment operator\n";
int len = strlen(other.m_pString);
m_pString = new char [len + 1];
strcpy(m_pString, other.m_pString);
return *this;
}
operator const char*()
{
return this->m_pString;
}
};
|