2

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;
    
} ```
  • 8
    The only way to abort a constructor is to throw an exception from it. – HolyBlackCat Jan 06 '21 at 10:42
  • Is this really a property of a class or rather property of your use scenario in which case you should do the check **before** you even attempt to create an object. As for constructor, you can always throw an exception. – Michał Kaczorowski Jan 06 '21 at 10:56
  • 2
    `delete this` in a constructor will cause any usage of the object (who's construction has been ended) to have undefined behaviour. Throw an exception instead - the net effect for the caller is that the object has never existed. – Peter Jan 06 '21 at 10:57

1 Answers1

2

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
}
Holt
  • 21
  • 1
  • 3
    Better change that function to hand out a `std::unique_ptr`. `std::optonal` is another good option for a return type. – πάντα ῥεῖ Jan 06 '21 at 11:03
  • @πάνταῥεῖ would either of you recommend to make this function a class level function of the returning type (i.e. `static bar::`) or a method of the requesting object, or a global non-method function alltogether? – Vroomfondel Jan 06 '21 at 11:29
  • @Vroomfondel _shrug_ – πάντα ῥεῖ Jan 06 '21 at 11:32
  • 1
    @Vroomfondel depends on your usage/structure realy. If you want, you can make this a static function in the class and hide/ = delete the default constructor. This way you gaurentee other users make use of that function. – Holt Jan 06 '21 at 11:40