Please code in c++ --------------------------------------- Assume you have a cla
ID: 3732779 • Letter: P
Question
Please code in c++
---------------------------------------
Assume you have a class called StringVar whose values are strings. StringVar objects will be string variables. StringVar objects use dynamic arrays whose size is determined when the progrm is running. It is a class using a dynamic array as a member variable.
StringVar has three constructors, one that takes an int as its argument, and determines the length from that. The second is the default, and create string objects of 100 bytes in length. The third one takes a c-string as the argument, and determines the length from this c-string argument, and copies the c-string into the object's string value.
Following the code, complete the copy constructor for this class:
// THE HPP FILE
#include
using namespace std;
class StringVar
{
public:
StringVar(int size);
StringVar();
StringVar(const char arr[]);
StringVar ... the copy constructor protype intentionally omitted
~StringVar();
int length() const;
private:
char *value; //pointer to dynamic array that holds the string value.
int max_length; //declared max lengthh of any string value.
};
//THE CPP FILE
#include
#include
#include
using namespace std;
//Uses cstring:
int StringVar::length()const
{
return strlen(value);
}
StringVar::StringVar(int size) : max_length(size)
{
value = new char[max_length + 1]; //+1 for ''.
value[0] = '';
}
StringVar::StringVar() : max_length(100)
{
value = new char[max_length + 1]; //+1 is for ''.
strcpy(value,a);
}
//YOUR CODE HERE
//Code the copy constructor here. Remember it's dynamic, and also leverage the included functionality for c-strings
Hint: try strcpy
Explanation / Answer
Following is the code based on your ques. Hope this helps , in case of any quesry do ask me in comments:-
StringVar::StringVar(char const *str)
{
int size = 0, i = 0;
StringVar s;
while (str[i++] != '')
size++;
s.value = new char[size + 1]; //+1 is for ''.
strcpy(s.value,str);
}