Answer the question
In order to leave comments, you need to log in
Why do we lose data of type string in c++?
Class:
#include "Person.h"
#include <cstring>
#include <string>
using namespace std;
class Adult :
public Person
{
public:
Adult();
~Adult();
std::string GetDescription();
static void RandAdult(Adult * adult);
Person* MarriedOn = nullptr;
int GetAge();
void SetAge(int age);
string WorkPlace = (string)"";
};
std::string Adult::GetDescription()
{
string tmpS = Surname + " " + Name + ", " + IntToStr(Age) + " years old," + SexToStr(sex);
if (MarriedOn == nullptr)
{
tmpS = tmpS + ", single";
}
else
{
tmpS = tmpS + ", married on "+MarriedOn->Name+" "+MarriedOn->Surname;
}
if (WorkPlace.length()>0)
{
tmpS = tmpS + ", " +WorkPlace;
}
else
{
tmpS = tmpS + ", unworked";
}
return tmpS;
}
An unhandled exception occurred at 0x752AA6F2 in LAB6_5152.exe: Microsoft C++ exception: std::bad_alloc at memory address 0x0019E050.
tmpS = tmpS + ", " +WorkPlace;
Answer the question
In order to leave comments, you need to log in
@MarkusD
Objects of type Person were stored in the list by value; when an object of type Adult was added to the list, only Person data was copied. After that, casting the Person type to the Adult type became meaningless, and calling the `GetDescription()` function led to an object memory overflow and caused a memory access error.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question