Pages

Thursday, June 23, 2011

Constructor - 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;
}
};

0 comments:

Post a Comment