Get premium membership and access questions with answers, video lessons as well as revision papers.

Given this particular defined class; class strtype { char *p; int len; public: char *getstring() { return p;} int getlength() { return len;} add two constructor functions. Have the first one...

      

Given this particular defined class;

class strtype {
char *p;
int len;
public:
char *getstring() { return p;}
int getlength() { return len;}
add two constructor functions. Have the first one take no parameters. Have this one allocate 255 bytes of memory (using new), initialize that memory as a null string, and give len a value of 255. Have the other constructor take two parameters. The first is the string to use for initialization and the other is the number of bytes to allocate. Have this version allocate the specified amount of memory and copy the string to that memory. Perform all necessary boundary checks and demonstrate that your constructors work by including a short program.

  

Answers


Davis
#include
#include
#include
using namespace std;
class strtype {
char *p;
int len;
public:
strtype();
strtype (char *s, int l);
char *getstring() {return p;}
int getlength() {rn len;}
};
strtype::strtype()
{
p = new char[255];
if(!p) {
cout << "Allocation error\n";
exit(1);
}
*p = '\0'; // null string
len =strtype::strtype(char *s, int l)
{
if(strlen(s) >= l) {
cout << "Allocating too little memory!\n";
exit(1);
}
p = new char [l];
if(!p) {< "Allocation error\n";
exit(1);
}
strcpy(p, s);
len = l;
}
int main()
{
strtype s1;
strtype s2("This is a test", 100);
cout << "s1: " <cout <cout << "s2: " << s2.getstring() << " -Length: ";
cout << s2.getlength() << '\n';
return 0;
}.

Githiari answered the question on May 29, 2018 at 17:54


Next: Explain what is wrong with the following program and then fix it. // This program contains an error. #include #include using namespace std; class myclass { int *p; public: myclass(int i); ~myclass()...
Previous: Explain the purpose of copy constructor and how it differs from a normal constructor.

View More Computer Science Questions and Answers | Return to Questions Index


Learn High School English on YouTube

Related Questions