Skip to main content

Join two strings with dynamic constructor

Write a C++ program to join two strings using dynamic constructor concept.

A dynamic constructor is a constructor that allocates memory at run time with the new operator. It is useful when the size of the data is not known beforehand, such as the length of a string. The memory is released in the destructor with delete.

To join two strings, we use a constructor that takes two String objects, allocates len1 + len2 + 1 bytes, and copies both strings into it.

#include <iostream>
#include <cstring>
using namespace std;

class String {
    char *str;
    int len;
public:
    String() { len = 0; str = new char[1]; str[0] = '\0'; }

    // dynamic constructor: allocates memory for the given text
    String(const char *s) {
        len = strlen(s);
        str = new char[len + 1];
        strcpy(str, s);
    }

    // dynamic constructor that joins two strings
    String(String &a, String &b) {
        len = a.len + b.len;
        str = new char[len + 1];      // memory sized at run time
        strcpy(str, a.str);
        strcat(str, b.str);
    }

    void show() { cout << str << "  (length " << len << ")" << endl; }

    ~String() { delete[] str; }       // free memory
};

int main() {
    String s1("Object ");
    String s2("Oriented");
    String s3(s1, s2);                // join s1 and s2

    s1.show();
    s2.show();
    s3.show();
    return 0;
}

Output:

Object   (length 7)
Oriented  (length 8)
Object Oriented  (length 15)

Working: new char[len + 1] reserves exactly enough space (one extra byte for '\0'). strcpy copies the first string and strcat appends the second. The destructor frees each object's memory when main() ends.

Note: if objects are copied with the default copy constructor, two objects would share one pointer. For real use, add a user-defined copy constructor and assignment operator.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 4 questions →