Answer to Question #267228 in C++ for wangyo

Question #267228

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. 



1
Expert's answer
2021-11-17T06:30:11-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS