- 2070 Chaitra · 7 marks
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)
Related questions
- Simple program illustrating OOP concept · Object Oriented Programming, chapter 1
- Constructor and destructor order, multilevel inheritance · Object Oriented Programming, chapter 6 · asked 2×
- Department class constructor and destructor · Object Oriented Programming, chapter 4
- Dynamic memory allocation with new and delete · Object Oriented Programming, chapter 3 · asked 2×
- Add objects of two different classes · Object Oriented Programming, chapter 4 · asked 2×
- Compare two strings with function · Computer Programming, chapter 7
- Stored program concept and processing cycle · Microprocessor, chapter 1 · asked 6×
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9
- Dynamic balancing with two correction planes · Theory of Mechanism and Machine II, chapter 5