Question

I have this class MyClass that, most often, is created by parsing a string. I cannot trust that this string is always correct and therefore I do not want to put the parsing in the constructor. Hence, I have created a static parsing function that returns true if the string is valid and false if it is invalid. See below:

class MyClass
{
private:
    Type1 m_memberA;
    Type2 m_memberB;

public:        
    MyClass(const Type1& parameterA, const Type2& parameterB)
         : m_memberA(parameterA), m_memberB(paramterB)

    static bool parse(const std::string& input, MyClass * result)
    {
        Type1 paramA;
        Type2 paramB;

        //Parse input and get values for paramA and paramB.
        //Return false if the input is invalid.

        MyClass temp(paramA, paramB)
        *result = temp;
        return true;
    }
}

My intent was to use it as follows:

void myFunction(const std::string& input)
{
     MyClass * myObject = NULL;
     if(MyClass::parse(input, myObject))
     {
          //Use myObject for something
     }
     else
     {
          //Log invalid input string
     }
}

Now, this crashes at run time. And I figured that is because I am trying to de-reference a NULL-pointer, which obviously doesn't work. How can I fix this?

Was it helpful?

Solution

You need to pass either a pointer-to-pointer to the function or a pointer reference and allocate with new:

static bool parse(const std::string& input, MyClass *& result)
    {
        // ......

        result = new MyClass(paramA, paramB)
        return true;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top