A
A
Andrey Golubkov2016-11-13 15:12:52
OOP
Andrey Golubkov, 2016-11-13 15:12:52

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 error occurs while working with the WorkPlace field.
Error while running the program:
An unhandled exception occurred at 0x752AA6F2 in LAB6_5152.exe: Microsoft C++ exception: std::bad_alloc at memory address 0x0019E050.

Error line:
tmpS = tmpS + ", " +WorkPlace;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Golubkov, 2016-11-14
@Android97

@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.

1
15432, 2016-11-13
@15432

string WorkPlace = (string)"";
replace with
string WorkPlace = string("");
or generally on
string WorkPlace;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question