So there seems to be some problem with the solution to Problem 9-2 in the book "Object-Oriented Programming in C++, 4th edition" by Robert Lafore. So the problem is that if I would like to create a Pstring object with a statement like Pstring = "This is a string"
, the Pstring constructor will only call the constructor with no arguments in the String class, instead of the second one with uses one char[] argument. Does anyone know what causes this kind of problem, and a fix to this? Thanks!
#include <iostream>
#include <cstring>
using namespace std;
////////////////////////////////////////////////////////////////
class String //base class
{
protected: //Note: can't be private
enum {
SZ = 80
}; //size of all String objects
char str[SZ]; //holds a C-string
public:
String() //constructor 0, no args
{
str[0] = '\0';
}
String(char s[]) //constructor 1, one arg
{
strcpy(str, s);
} // convert string to String
void display() const //display the String
{
cout << str;
}
operator char*() //conversion function
{
return str;
} //convert String to C-string
};
////////////////////////////////////////////////////////////////
class Pstring: public String //derived class
{
public:
Pstring(char s[]); //constructor
};
//--------------------------------------------------------------
Pstring::Pstring(char s[]) //constructor for Pstring
{
if (strlen(s) > SZ - 1) //if too long,
{
for (int j = 0; j < SZ - 1; j++) { //copy the first SZ-1
str[j] = s[j]; //characters "by hand"
str[j] = '\0';
} //add the null character
} else
//not too long,
String(s); //so construct normally
}
////////////////////////////////////////////////////////////////
int main() { //define String
String s1 = "This is a string"; // This works great
s1.display();
Pstring s2 = "This is a string"; // *** Here, nothing will be assigned to s2****
s2.display(); // *** Nothing will be printed here***
return 0;
}