Search code examples
c++boost

cpp: error: 'class boost::optional<std::__cxx11::basic_string<char> >' has no member named 'c_str'


I am new to c++ and trying to fix an issue in my function -

Test::Test(const boost::optional<std::string>& name):
    mName(name)
{
        ...
        Some statements
        ...
}

int Test::setResult()
{
     ...
     i=system(mName.c_str())
     ...
}

The error I am getting is

error: 'class boost::optional<std::__cxx11::basic_string<char> >' has no member named 'c_str'
     i=system(mName.c_str());
                    ^

Please help to fix the my code


Solution

  • The mName member is of the optional type. If you want the string behind that optional, you need to dereference it with something like:

    i = system(mName->c_str());
    

    Of course, you probably want to first ensure it has a value:

    if (mName) i = system(mName->c_str());