Constructors can be used to initialize member objects as well as allocate memory. This can allow an object to use only that amount of memory that is required immediately. This memory allocation at run-time is also known as dynamic memory allocation. The new operator is used for this purpose.
Sample Program
The program below shows the use of new in constructors of a simple String class.
/* * Program to illustrate use of dynamic memory allocation * in constructors * https://www.tech-faq.com */ #include #include class String { private: char *arr; int size; public: String():size(0) // Constructor no. 1 { arr = new char[size+1]; } String(char *s):size(strlen(s)) // Constructor no. 2 { arr = new char[size+1]; // one additional byte for '\0' null terminator strcpy(arr, s); } void show() { std::cout << arr << std::endl; } void join(String &a, String &b) { size = a.size + b.size; delete arr; arr = new char[size+1]; strcpy(arr, a.arr); strcat(arr, b.arr); } }; int main(void) { char *name = "John Carry"; String name1(name); String name2("Mark Wills "); String name3("Malcolm Marshall"); String s1, s2; s1.join(name1, name2); //i.e. s1 = name1 + name2 s2.join(s1, name3); name1.show(); name2.show(); name3.show(); s1.show(); s2.show(); return 0; }
Output
John Carry Mark Wills Malcolm Marshall John CarryMark Wills John CarryMark Wills Malcolm Marshall
Explanation
Two constructors are used in the above program. The first is the default (non-parameterized) constructor which initializes size to 0 and dynamically allocates 1 byte of memory to the char* array arr. The second constructor initializes the size to the size of the string entered by the user and then dynamically allocates size +1 bytes of memory for arr. Note that here we have initialized the size of the arr array with 1 byte more than that entered by the user; this is to make place for the null terminator (‘\0’) or end-of-string character.
In the above program we have used the standard library functions strcpy() and strcat(). strcpy() copies character strings from one memory location to another and strcat() joins two strings into one.
The class member function join() concatenates two strings and allocates the result to the current object. In main(), the program uses this function to concatenate three strings.
Follow Us!