I am trying to do a homework assignment where we insert a string into a string at a specified point using a linked stack, hence the struct and typedef. Anyway, when I try to access stringLength in the StringModifier class inside the InsertAfter method, I get a run time error and I cannot figure out what the problem is. I should be able to access and modify the variable because it's protected and the derived class is inherited publicly.
struct StringRec
{
char theCh;
StringRec* nextCh;
};
typedef StringRec* StringPointer;
class String
{
public:
String();
~String();
void SetString();
void OutputString();
int GetLength() const;
protected:
StringPointer head;
int stringLength;
};
class StringModifier : public String
{
public:
StringModifier();
~StringModifier();
void InsertAfter( StringModifier& subString, int insertAt );
};
void StringModifier::InsertAfter( StringModifier& subString, int insertAt )
{
// RUN TIME ERROR HERE
stringLength += subString.stringLength;
}
in MAIN
StringModifier test;
StringModifier test2;
cout << "First string" << endl;
test.SetString();
test.OutputString();
cout << endl << test.GetLength();
cout << endl << "Second string" << endl;
test2.SetString();
test2.OutputString();
cout << endl << test2.GetLength();
cout << endl << "Add Second to First" << endl;
test.InsertAfter( test2, 2 );
test.OutputString();
cout << endl << test.GetLength();
//String Class
String::String()
{
head = NULL;
stringLength = 0;
}
String::~String()
{
// Add this later
}
void String::SetString()
{
StringPointer p;
char tempCh;
int i = 0;
cout << "Enter a string: ";
cin.get( tempCh );
// Gets input and sets it to a stack
while( tempCh != '\n' )
{
i++;
p = new StringRec;
p->theCh = tempCh;
p->nextCh = head;
head = p;
cin.get( tempCh );
}
stringLength = i;
}
void String::OutputString()
{
int i = stringLength;
int chCounter;
StringPointer temp;
// Outputs the string bottom to top, instead of top to bottom so it makes sense when read
while( head != NULL && i > 0 )
{
temp = head;
chCounter = 0;
while( temp != NULL && chCounter < (i-1) )
{
temp = temp->nextCh;
chCounter++;
}
cout << temp->theCh;
i--;
}
}
int String::GetLength() const
{
return stringLength;
}
The StringModifier class has empty constructors and destructors.