Software & Finance





C++ - Constructor





Constructors are the special type of functions provided in C++ and they will get called at the time of object definition automatically. 

MyString is the class name in the given sample code. All constructor functions will use the class name as the function name, only the argument might differ. Based on the arguments we have different types are constructors.

  • Default Constructor - the default constructor is defined in as MyString(), is nothing but the class name with no arguments.
  • Copy Constructor - Use the syntax. <classname>(const <classname> &other). Click here to know more about copy constructor
  • Parameterized Constructor - These constructors take any other arguments as input other than default and copy constructors. Refer to the syntax MyString(const char *p) in the sample code.

Remember the following points in constructor


  1. There is no virtual constructor.
  2. Constructor can not return any value.
  3. If you have to return any value from constructor, then use the exceptions.
  4. Constructors can be called implicitly or explicitly.
  5. They 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.
  6. 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;

    }

   

};