C++ deleteting object in constructor?

Viewed 66

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;
    
} ```
1 Answers

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
}
Related