c++ assignment help

Hi- I am taking a c++ course at school (a requirement from my work) and need help with this question.
**this is not a exam question- just an assignment our instructor gave**

Continue the implementation of the String class. Add each of the following

A constructor String(int n, char c) that initializes the string with n copies of
the character c.
• The + operator to perform concatenation of two String objects.
• A member function compare(String) that returns –1, 0, or 1 depending upon
whether the string is lexicographically less than, equal to, or greater than the
argument. Then, using this member function, provide definitions for the comparison
operators <, <=, ==, !=, >, and >=.
• A function resize(int n, char c) that changes the size of the string to n, either
truncating characters from the end, or inserting new copies of character c.
• The function call operator, so that s(int start, int length) returns a substring
starting at the given position of the given size.


Here is the string class which I have already constructed.

[class String
{
public:
String(); // Default constructor
String(const char p[]); // Simple constructor
String(const String& right); // Copy constructor
~String(); // Destructor
String& operator=(const String& right); // Assignment operator
String& operator+=(const String& right);
int length() const;
char& operator[](int index);
char operator[](int index) const;
private:
char* buffer;
int len;
};
closed account (Dy7SLyTq)
what do you need help with. and just fyi (not that it matters) its actually
typedef basic_string<char> string
You haven't written any of the functions in the list.
Was there a specific question you had?
@Daleth- SO I have the basic string class.
I have to add the following to this class



•A constructor String(int n, char c) that initializes the string with n copies of
the character c.
• The + operator to perform concatenation of two String objects.
• A member function compare(String) that returns –1, 0, or 1 depending upon
whether the string is lexicographically less than, equal to, or greater than the
argument. Then, using this member function, provide definitions for the comparison
operators <, <=, ==, !=, >, and >=.
• A function resize(int n, char c) that changes the size of the string to n, either
truncating characters from the end, or inserting new copies of character c.
• The function call operator, so that s(int start, int length) returns a substring
starting at the given position of the given size.
Last edited on
Do you need an idea of how these functions are supposed to look?
Do you need help understanding how operator overloading works?
Are you having trouble with the code you have already written for the list?

Or is there no problem, and you haven't started writing these functions?

Or (I hope this isn't what you're requesting) do you need someone to do your homework for you?

Please be specific.

Also, take a look here:
http://www.cplusplus.com/forum/beginner/1/
Last edited on
@Daleth- I need help with the syntax formation- basically how the functions are supposed to look.
I will then want to take a stab at it myself.

Sorry- this is the first time I am posting on this forum. I took some Java classes long ago (8 yrs back) during my undergrad and since then haven't visited the programming domain- I work as a Project manager ;). So the confusion.
Part 1:

I'll try explaining each function and how it might look like. Note that there are different ways to write each function, though.

•A constructor String(int n, char c) that initializes the string with n copies of the character c.

I'm going to assume you already know the basics of what a constructor is and what it does. Here, this constructor String::String(int n, char c) is going to 1) make a c-string of length n and 2) fill it with c's. Now, you also have these two member variables: char* buffer and len. So here's a code snippet:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
String::String(int n, char c)
      //The following is called an initialization list. If you've not gone over this
      //   yet, just ignore this part and have len = n in the function body.
   : buffer(nullptr) 
   , len(n)
{  //Function body
   //The first task of the constructor is to create a string of length n,
   //   so you need to make buffer point to an array on the heap.
   //   Hint 1: new
   //   Hint 2: Because this will be a c-string, you need to allocate
   //      n+1 units to make room for the null-terminating character (\0).
   buffer = ???;
   //Now you want to fill the buffer with c
   for(int I = 0; I < n; ++i) //notice "I < n" and not "I < n+1".
   {                        // Remember that the last character will be '\0'
      //You have two choices to assign c to each position in the c-string
      *( ??? ) = c; //Pointer arithmetic or
      ??? [ ??? ] = c; //Subscript operator
   }
   *(buffer + n) = '\0'; //Very important you don't forget this
}




• The + operator to perform concatenation of two String objects.

String concatenation is basically joining two strings together, i.e. "123" + "456" will become "123456".
In addition, the basic syntax of an operator function is:
1
2
3
Return_type operatorSymbol(Arg1, arg2);
//In this case, you want to return a String, the operation is +,
//   and the arguments are also Strings, so both are const String&. 

There will be one special aspect about this non-member function, however. This will be a friend function, so it can access private variables in the class. So the prototype in the class would look like:
1
2
3
4
5
6
7
8
class String{
   public:
//...
      friend String operator+(const String&, const String&);
//...
};

String operator+(const String&, const String&); //Note that we still need this 

And so the implementation might look like:
1
2
3
4
5
6
7
String operator+(const String& lhs, const String& rhs){
   String toreturn; //Declare a String object that contains the result
   toreturn.len = lhs.len + rhs.len; //This is legal because this function is a "friend".
   //Here I will leave you to figure out how to manipulate toreturn.buffer to
   //   be long enough to hold lhs.buffer and rhs.buffer together, and how to
   //   copy over the c-strings.
}

Another option for this function is to not make it a friend and to use the newly written constructor String::String(int n, char c). So your function might then look like:
1
2
3
4
5
6
String operator+(const String& lhs, const String& rhs){
   String toreturn(lhs.length() + rhs.length(), ' ');
   //This calls your new constructor and fills it with spaces
   //Now all you have to do is use other functions, like String::operator[]
   //   to replace the c-string in toreturn.
}
Part 2:

• A member function compare(String) that returns –1, 0, or 1 depending upon
whether the string is lexicographically less than, equal to, or greater than the
argument. Then, using this member function, provide definitions for the comparison
operators <, <=, ==, !=, >, and >=.

Basically, the compare function will return one of the three values based on:
1) -1: The second string is longer or the characters are "larger"
--Ex: "abc" compared with "abcd" or "abc" compared with "bdp"
2) 0: The two strings are identical. Self-explanatory.
3) 1: The second string is shorter or the characters are "smaller"
--Ex: "abcd" compared with "abc" or "bdp" compared with "abc"
So, assuming this is a member function, it might look like:
1
2
3
4
5
6
7
8
9
10
//Mark this as read-only (const at the end) since this function should not
//   be modifying anything. I'll also explain why this is useful later.
int String::compare(const String& sec) const{ 
   if(len < sec.len) return -1; //Shorter
   else if(len > sec.len) return 1; //Longer
   //If both conditions above fail, we know that they are of equal length,
   //   so now you compare each individual character. Hint: A char has an
   //   ASCII value, so you can write stuff like 'a' < 'b' == true as if it were
   //   an int.
}

Once you've finished writing this function, you can use it to write your comparison operators in a flash. Because they're so trivial, I'll jot down all of them here (These don't need to be members or friends):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
bool operator==(const String& lhs, const String& rhs){
   return (lhs.compare(rhs) == 0);
}
bool operator!=(const String& lhs, const String& rhs){
   return !(lhs == rhs); //Calls previous function and reverses result
}
bool operator<=(const String& lhs, const String& rhs){
   return (lhs.compare(rhs) == 0 || lhs.compare(rhs) == -1);
}
bool operator>=(const String& lhs, const String& rhs){
   return (lhs.compare(rhs) == 0 || lhs.compare(rhs) == 1);
}
bool operator<(const String& lhs, const String& rhs){
   return (lhs.compare(rhs) == -1);
}
bool operator>(const String& lhs, const String& rhs){
   return (lhs.compare(rhs) == 1);
}

Note that I called compare() in each function. Here's a kicker: if compare() wasn't read-only, the compiler would refuse to compile this code. Why? Because that const at the end guarantees that the objects won't be modified. Since the parameters are const, you may only call member functions marked as read-only, so the compiler knows you aren't doing something illegal like modifying a const object.


• A function resize(int n, char c) that changes the size of the string to n, either truncating characters from the end, or inserting new copies of character c.

The instruction is pretty clear. If you call resize(5, 'W') on a string holding "abc", the result should look like "abcWW" and resize(1, 'Q') would result in "a". Here's a code snippet (this function, too, should be a member function):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void String::resize(int n, char c){
   char* hold = buffer; //Be sure to keep the old c-string temporarily
   buffer = ???; //Similar to one line in the constructor I gave hints about
                //   Remember to make room for '\0' !
       //Copy back cstring without '\0';
   for(int i(0); i < len; ++i)
      ???;
      //Now "fill" the string if the new length is longer
   for(; len < n; ++len)
      *( ??? ) = c;
   len = n; //In case len > n
//hold now points to unused data on the heap; remember to free that memory
   delete[] hold;
}

For this function, you should consider having a default value for char c.


• The function call operator, so that s(int start, int length) returns a substring starting at the given position of the given size.

I'm surprised you guys aren't just making String::substr(). The function call operator is ( ) as in:
1
2
String myString;
String substring = myString(3, 6);

The result is what's called a "function object", or a "functor". Like the other operators, the function call operator follows the same basic prototype syntax. The only difference is that there are no restrictions on how many arguments it can take. For what this assignment asks of you, it might look like (my function will use some of the other member functions, but you don't have to do the same thing):
1
2
3
4
5
6
String String::operator() (int start, int length){
   String toreturn(length, ' '); //Again, to hold the results; new constructor
   for(; length > 0; --length)
      ??? = ???; //Overloaded subscript operator
   return toreturn;
}


Hope this helps (if it wasn't superfluous for you).
@Daleth
this helped:)
One more question please
B. Our String class always deletes the old character buffer and reallocates a new character buffer on assignment or in the copy constructor. This need not be done if the new value is smaller than the current value, and hence would fit in the existing buffer. Can we rewrite the String class so that each instance will maintain an integer data field indicating the size of the buffer, then only reallocate a new buffer when necessary. Abstract the common tasks from the assignment operator and the copy constructor, and place them into an internal method?
This was another requirement which I forgot to post.
Any help would be appriciated
Topic archived. No new replies allowed.