Chapter:9 Inheritance, solved Exercise question book by Robert Lafore
OOP BY ROBERT LOFORE
4th Edition
Chapter:9
Inheritance
Question no 2;
Recall the STRCONV example from Chapter 8. The String class in this example has a flaw: It does not protect itself if its objects are initialized to have too many characters. (The SZ constant has the value 80.) For example, the definition String s = “This string will surely exceed the width of the “ “screen, which is what the SZ constant represents.”; will cause the str array in s to overflow, with unpredictable consequences, such as crashing the system. With String as a base class, derive a class Pstring (for “protected string”) that prevents buffer overflow when too long a string constant is used in a definition. A new constructor in the derived class should copy only SZ–1 characters into str if the string constant is longer, but copy the entire constant if it’s shorter. Write a main() program to test different lengths of strings.
Program Source code:
#include <iostream>
#include <conio.h>
#include<cstring>
using namespace std;
class String
{
protected:
enum { SZ = 80 }; //max size of Strings
char str[SZ]; //array
public:
String() //constructor, no args
{
str[0] = '\0';
}
String(char s[]) //constructor, one arg
{
strcpy(str, s);
}
void display() //display string
{
cout << str;
}
void concat(String s2) //add arg string to
{ //this string
if (strlen(str) + strlen(s2.str) < SZ)
strcpy(str, s2.str);
else
cout << "\nString too long";
}
};
class Pstring :public String
{
public:
Pstring()
{}
Pstring(char s[])
{
int len = strlen(s);
if (len < SZ)
strcpy(str, s);
else
{
for (int i = 0; i < (SZ); i++)
{
str[i] = s[i];
}
}
}
};
int main()
{
Pstring s, s1;
s = "Awais Irfan";
s1 = "This string will surely exceed the width of the screen, which is what the SZ constant represents.";
s.display();
cout << endl;
s1.display();
cout << endl;
_getch();
}
Program output in Dev c++ :
Comments
Post a Comment