Search code examples
c++stringobjectconstructornlp-question-answering

C++ deleteting object in constructor?


i want to make class which has one string atributte. But if string has length more then 50 characters i dont want create object. What should i do?

{
    if (paSlovo.length() <= DLZKA_SLOVA)
        aSlovo = paSlovo;
    else
        delete this;
    
} ```

Solution

  • Instead of doing this trough the constructor you can do this with a function that will either provide you with the object if the criteria is met or you get a nullptr.

    Make sure to correctly delete the object when done or make use of smart ptrs

    //create object
    bar* TryCreateMyObj(string const& paSlovo) const
    {
        //only create object if string is less than 50
        if (paSlovo.length() <= DLZKA_SLOVA)
        {
            return new bar();
        }
        return nullptr
    }