Create a class called STRING, the class has two private member str and size of String and int type respectively. Provide a copy constructor for the class that initialize objects with other object. Write member function for the class that show the string and size for each object.Â
#include<iostream>
#include<cstring>
using namespace std;
class String {
  char *str;
  int size;
public:
  String(const char *s = NULL);     // constructor
  ~String() { delete [] str; }     // destructor
  String(const String&);        // copy constructor
  void display () {
  cout << "size = "<< size<< "  "<< str << endl; } // Function to displat size and string
 };
 // constructor
String::String(const char *s ) {
  size = strlen(s);
  str = new char[size+1];
  strcpy(str, s);
}
 // copy constructor
String::String(const String& old_str) {
  size = old_str.size;
  str = new char[size+1];
  strcpy(str, old_str.str);
}
int main() {
  String ob_str1("i love c++");  // constructor
  String ob_str2 = ob_str1;       // copy constructor
  ob_str1.display();
  ob_str2.display();
  return 0;
}
Comments
Leave a comment