• Sonnenblume@discuss.tchncs.de
    link
    fedilink
    arrow-up
    7
    ·
    2 days ago

    There are lots of ways to write C++ code that looks perfectly reasonable but introduces horrible undefined behaviour. You need to be aware of lots of edge cases all the time and you will still make mistakes that can introduce difficult to trace bugs. One of my personal favourites is object slicing.

    class A {
       int foo;
    };
    
    class B : public A {
       int bar;
    };
    
    B b;
    A a = b;
    

    Looks OK? Well, a now only contains the A part of the object. The field bar is lost in the assignment. There are reasons for this behaviour but its a sharp edge nonetheless.

    These kinds of problems are numerous and you have to keep them in mind while programming C++. Some people don’t mind it but many do. Static analysis tools that can catch many of these errors exist, but I understand people who say they don’t want to deal with that and rather use a language where these kind of errors are not possible. Personally, I would also discourage people from starting new C++ projects today if they can avoid it.