c++classdefinitionconstructctor-initializer

Problem while initializing attribute in constructor c++


While i try to debug ERROR appear : "Unhandled exception at 0x5784F2F6 (ucrtbased.dll) in Final project.exe: An invalid parameter was passed to a function that considers invalid parameters fatal." Tried every thing can't figure out how to solve this.

using namespace std;
class Map :
{
private:
    double *mhours_played;
    string *maps;
    unsigned element_num;
public:
    Map() 
    {
         maps[2] = { "Summoner's rift", "Aram" };
         element_num = 2; mhours_played[2] = {};
    }

    ~Map() { delete[] maps; }
};

Solution

  • These statements

    maps[2] = { "Summoner's rift", "Aram" };
    mhours_played[2] = {};
    

    do not make sense. maps and mhours_played are pointers that within the body of the constructor have indeterminate values. They are not arrays as you think. For example the expression maps[2] is a scalar object of the type std::string.

    Define the constructor at least like

    Map() :  mhours_played( new double[2]() ), 
             maps( new std::string[2] { "Summoner's rift", "Aram" } ),
             element_num( 2 )
    {
    }
    

    and the destructor like

    ~Map() 
    { 
        delete[] maps; 
        delete[] mhours_played;
    }