Answer to Question #179412 in C++ for Waleed Abid

Question #179412

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-04-09T12:28:34-0400
#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 show () {
    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("MY TEXT HELLO!!!");   // constructor
    String ob_str2 = ob_str1;             // copy constructor
 
    ob_str1.show();       
    ob_str2.show();
 
    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