Write a C++ program to create class 'String', create a data member of the of class that can be dynamically created with parameterized constructor and releases the memory with destructor.
Aug 15, 2018This program, requires the concept of pointer. We are creating a class String that holds the character array as data member, and that can be initialized during object creation dynamically. The allocated memory is released after the object deletion or when the object goes out of scope. This program requires the following concepts.
- pointers
- dynamic memory allocation with new and delete operator
- parameterized constructor in C++
- sizeof operator
- constant data type
// program to create a class "String" // which has data member of character // array, which is dynamically allocated during object creation // and the memory allocated is released by destructor #include<iostream> using namespace std; class String{ private: char *string_array; //string array pointer public: String(const char *in_str)//parameterized constructor { int SIZE_STRING = sizeof(in_str); //allocating memory string_array = new char[SIZE_STRING + 1]; // copying all the string characters for (int i = 0; i < SIZE_STRING; i++) { *(string_array + i) = *(in_str + i); } // finally apending nulll character at the end *(string_array + SIZE_STRING) = '\0'; } void display(){ cout<<string_array<<endl; } ~String(){ // releasing the memory with destructor delete [] string_array; } }; int main(){ String mystring("I am ram"); mystring.display(); return 0; }
SAMPLE RUN :
I am ram