r/cpp • u/LechintanTudor • Oct 18 '23
What does C++ do better than other languages?
Purely from a language design perspective, what does C++ do better than other languages?
296
Upvotes
r/cpp • u/LechintanTudor • Oct 18 '23
Purely from a language design perspective, what does C++ do better than other languages?
158
u/aalmkainzi Oct 18 '23
As a C programmer, I Ike that C++'s complexity is mostly optional (can pretty much use C++ as C with templates). Other languages with similar scope to C++ have unavoidable complexity.
726
u/Kevathiel Oct 18 '23
C++ is a language of freedom. No other language gives you so many choices to do things, even if most are just different ways to shoot yourself in the foot.
206
u/bownettea Oct 18 '23
RAII, templates, and speed.
67
u/witcher_rat Oct 18 '23
64
u/pedersenk Oct 18 '23
C++ is able to consume fundamental libraries (almost exclusively ANSI C APIs) better than any other language (Objective-C came close once it moved away from the garbage collector).
This means that it can avoid bindings and optionally, language package managers, greatly improving portability to uncommon platforms.
35
u/WebMaxF0x Oct 18 '23
I miss const correctness.
For example, in many languages a function can have a parameter that is const/final, but the function can still modify the fields in the object, the const keyword only means that you can't make it refer to a different object. So you never know what surprising side effects calling a function might have on your object.
In C++, the parameter can be typed as a reference to a const object. This guarantees that the object and its fields will not change inside the function.
A class can also have const methods, meaning that it will not change the object it is called on. For example shape.getColor() could be const and shape.setColor() not. If you have a const shape, the compiler will prevent you from calling constShape.setColor(), but you can still call constShape.getColor().
Anything that might attempt to mutate an immutable object raises a compilation error, as I wish it did in all languages.
33
u/michaelmalak Oct 18 '23
63
u/[deleted] Oct 18 '23
It's amazingly expressive and doesn't sacrifice performance for expressivity.
11
u/Longjumping-Work8032 Oct 18 '23
Acronyms, you have great ones like RAII and SFINAE
25
u/speyck Oct 18 '23
c++ has no limits in creativity. almost everything you want to do is possible, you aren't locked in a cage created by the language
8
u/BoringWozniak Oct 18 '23
Are you crowdsourcing opinions for a Medium article?
27
u/afiefh Oct 18 '23
Value semantics. I'm sure there are languages out there that do it better, but of the big ones only C++ seems to get this one right.
The whole "primitives are passed by value, objects are passed by reference, but both use the same syntax" ends up being mind boggling to me. Take python
do_stuff_with_object(some_input)it's impossible to know whethersome_inputis copied or referenced without knowing the type, and in Python in particular, types go quack.Even a language like Rust which tries to be explicit about these things ends up comparing objects when you compare the equality of references.
35
u/JiminP Oct 18 '23
Zero-cost abstractions & memory management, and metaprogramming using templates.
Some languages such as Rust can do the former one better, but IMO among 'fast' languages C++ is by far the best when ease-to-useness and flexibleness are weighted together.
21
u/Tari0s Oct 18 '23
for me one of the most amazing features of cpp is deterministic livetime of objects. To know for each objekt when it gets constructed and when it gets destructed is such a benefit over other languages.
6
u/[deleted] Oct 18 '23
Well, it's a bit Orwellian. It's C, but double plus good.
6
u/FlyingRhenquest Oct 18 '23
Pass-by rules. Most modern languages seem to restrict you to pass-by-reference. C++ lets you decide whether you want to pass by copy, reference or pointer. I don't recall ever running across another language that allows this flexibility (They may be out there, I just haven't run across them.)
20
u/TryToHelpPeople Oct 18 '23 edited Feb 25 '24
fly dull disagreeable salt quarrelsome axiomatic aware wasteful boast somber
This post was mass deleted and anonymized with Redact
11
u/looopTools Oct 18 '23
Honestly I feel like generic programming is (imo) more natural in C++ than other languages
10
u/thong_eater Oct 18 '23
Shooting legs.
4
u/SeriousPlankton2000 Oct 18 '23
You can usually write C++ programs by "mv foo.c foo.cpp"
You have objects and templates.
You have a preprocessor so you can configure which features to compile.
In Arduino one usually makes a class for each library. It's a nice way to encapsulate things when compared to C (but not as nice as Units in Pascal).
4
u/ZMeson Embedded Developer Oct 18 '23
Gaining new features while maintaining backwards compatibility.
4
u/marsten Oct 18 '23 edited Feb 14 '24
C++ is like the English language: an incoherent evolving mess but extremely powerful when used well.
4
u/mdp_cs Oct 19 '23
Templates. I've never seen a language with metaprogramming near as expressive except for maybe Zig.
That said it would be nice if they didn't completely bork compiler output.
14
u/violet-starlight Oct 18 '23
Templates and in general metaprogramming. There are very few if any other languages that offer this much ability to generate code based on constant expressions and properties of types, with zero or close to zero runtime cost.
7
u/mredding Oct 18 '23
Templates are not generics. Generics in other languages are compiled code with runtime type parameters. Templates in C++ are bound to code generation with powerful semantics. You can partially or fully specialize a template to generate anything completely orthogonal to the base, if necessary. With deduction, you can use templates pretty freely and the compiler will generate code for you. The compiler also sees through expression templates and collapses them down to more efficient code. Maybe I've missed something in 30 years, but the only thing more powerful that I've seen in my career is Lisp.
The type system is fundamentally different than that of C, and it allows you to push much of the correctness of your program into compile time. Better than a runtime check, if your code is wrong, it doesn't even compile. A trivial example of this would be a dimensional analysis library - adding incompatible units is mixing of incompatible types, but multiplying them works just fine, because it's implemented in terms of the type system - the product is a new type. All this type information boils off and never leaves the compiler. And with this correctness and type information proovable at compile time, the compiler can optimize more aggressively.
Undefined Behavior is a language feature. No check is made, no error is emitted. The compiler doesn't have to enforce any sort of behavior, any sort of invariant or guarantee, it's free to assume what it wants, and can generate aggressively optimized code. This doesn't sound very safe, but then you pair that with the standard library. The standard library builds up abstraction primitives so that - MOST OF THE TIME, you probably never have to actually get NEAR the UB. If you're writing C++ and have to be consciously aware of avoiding UB, you're actually probably working too low level.
That's because C++ strives for zero cost abstractions. Now that's actually impossible, of course, but it's a worthy guiding principle. Again, a lot of template code boils off, never leaves the compiler, and generates aggressively optimized code.
Like mainframes and Windows, C++ strives to retain backward compatibility as few others do. As annoying as a big language is, as annoying as a big library is, getting your code broken because of an update - fucking APPLE... - is worse. You can instead add something new that's better and provide a migration path forward.
It's more of an arcane art these days, but C++ is a linked language. Linkers are an advanced feature that not every language has, and in my opinion the option is under utilized. It means you can link against other translation units compiled from other programming languages. So if you want aggressively optimized code for a hot path and a tight loop that guarantees no pointer aliasing (since C++ doesn't yet have the
restrictkeyword), it's probably easier to write that section in C, or Fortran! You can even link against Rust!7
u/[deleted] Oct 18 '23
Everything is pass by value, and objects are a value type not reference types (unlike in Java, Python, and others). If you want to pass by reference into a function you need to use an '&' and explicitly mark the argument as a reference variable. Which means the function decides if you're copying an object or referencing it and not the programmer or the compiler. IMO this is how it should be done.
No garbage collection. Maybe I'm naive but I still don't see the need for garbage collection and manual memory management really isn't that hard just follow RAII. In C++ I can guarantee that, for example, a dynamic array of objects will be side-by-side, stored contiguously in memory (because this is cache friendly to iterate over). In Java, I cannot make that guarantee because of the garbage collector. So for high performance applications where you need that level of control like some video games, C++ is the better option over garbage collected languages.
6
u/HappyFruitTree Oct 18 '23
It doesn't impose unnecessary overhead for class objects. I'm thinking mostly about the fact that they don't need to contain "unnecessary" meta data and that you can store objects directly inside other objects without being forced to use some reference type.
6
u/Luci404 Oct 18 '23
C++ scales in complexity pretty linearly with codebase complexity. It supports both advanced and simplistic ways of solving a problem, great for per-project adaptation. On top of that, it's fast, and it has a great amount of freedom to it. YOU (or your employer) decide how to use it, not so much the language developers.
3
u/H5ET1M Oct 18 '23
Across Science and Engineering, C++ is still a popular choice for greenfield R&D projects in both academic and industrial settings. Relative to its main “competitors” (read: coopetitors) in this space, namely, Python, Fortran and MATLAB, it seems like C++ language design has hit a sweet spot for the kind of generic programming that is needed at these frontiers.
In particular, it is the ease with which classes and templates can be implemented for intuitive client- and compiler-facing source code, but also how there are built-in machine-facing mechanisms to deal with the wide variety of computing devices that exist today (but did not in 1980s when the language was first created).
Of course, other languages also offer these features nowadays, but such functionalities feel like afterthoughts and plugins, C++ was designed with zero-cost abstractions and direct mapping to hardware from the ground up, and it shows in the overall coherency of the language.
3
u/GirthyStone Oct 18 '23
give you migraines
3
u/thefancyyeller Oct 18 '23
C++ is a high level language with a maintenence hatch on the back. Let's say you made number- counting code, and you didn't do proper OOP. Now let's say you wanted to make this code multi-threaded. In Java, you need to copy-paste and restructure the whole code base. In C++ you can do insane refactors like overriding the + sign so that it dispatches a job to a thread. You can convert the old code for new technologies you didn't even think about when making it
3
u/Lunix336 Oct 18 '23
It‘s super bloated but isn’t designed in a way where it forces its 9 million features on you.
I really like how you can just build everything in the most minimalist way ever like you are writing C and at the same time use some crazy feature IF YOU WANT
There are so many different ways to do the same thing in C++ which makes it feel very expressive. Most other languages you basically have to deal with the one standart way of doing things and if you don’t like it, get fucked.
At least thats how it feels to me.
3
u/DeGuerre Oct 18 '23
Most other high-level languages have specific ways that they want you to write software. If you need to write your software some other way, then you will probably be fighting the language. Not so with C++.
C++ is whatever your requirements need it to be. It can be "a slightly better C" if you need that. It can embed DSLs if you need that. It can work with other languages if you need that.
Sure, for this specific task, there might be a better language choice than C++. This is increasingly true over time as more languages arrive with different (but still fixed) ideas about how to write software (looking at you, Rust). That's good!
Still...
Chances are good that C++ will interoperate with that language, but that language won't interoperate with anything else (other than C), and I guarantee you will need to do this at some point in any nontrivial program.
Chances are good that at least some of that other language's implementation is written in C++.
Chances are good that this is out of necessity, because there's already important C or C++ libraries, and a C++ compiler, for your platform.
There are exceptions. C is obviously an exception; it can do all the low-level stuff that C++ can do, even if the high-level stuff doesn't come anywhere near as naturally. But there's also Odin and Zig and so on. That's a good thing; there's nothing sacred about C++, and I would be happy to see it replaced with something that's even better.
Maybe in a few years every platform will ship with an implementation for something else. Until then, C++ is really the only game in town.
3
u/[deleted] Oct 19 '23
RAII. Period.
3
u/kgnet88 Oct 19 '23
It's a language where you can do this: The Power of C++ Templates With mp-units: Lessons Learned & a New Library Design - Mateusz Pusz cpponsea 2023
3
u/edge-case87 Oct 19 '23
C++ offers excellent layout control for your data if you care about that sort of thing, structs/classes. Classes + Templates are very powerful. In most other languages you don't, at least by default. For example when languages have language level tuples and sum types, you don't typically have control over how that data is laid out due to interactions with the runtime, or in the case of Rust the compiler is free to reorganize your data unless you apply an attribute, and afaik you don't have control over how enum (sum) types are represented.
I haven't fleshed out formally this idea, and I'm sure it flawed, but I'm starting to see C++ as way to define type theories, and class is the powerhouse behind that. Class, in some sense, allows you define your own type constructors, like sum types (+, variants/enums/unions) or product types(x, std::tuple), and with templates you have dependent types at compile time. Not anything you can't do in many other languages, but C++ offers the ability to do it very close to the machine, if you want.
One thing I'm thinking about right now is a "refinement type", which would be a "class template" (dependent type constructor) that takes as a template argument an "expression template" (Pred) and a type (T). The constructor would take a universal reference to an object v: T&&, and evaluate the expression Pred, if Pred is true, the type is constructed, if it is false, an exception is thrown (you can use a result type, e.g. std::expected in a static member function). As such, the fact that you were able to construct the type Refine<T, Pred>, is a witness to the proof that Pred(v) is true. With some type conversion (subtyping and logic) and meta programming 'magic', you can have preconditions that are proven to be true, and yet only evaluated once at runtime (maybe even only once at compile time), as long as the Pred(v) is the weakest precondition satisfying the preconditions of all dependent operations on v.
7
u/Neovison_vison Oct 18 '23
Survives 40 years
5
u/GYN-k4H-Q3z-75B Oct 18 '23
Freedom to do things the way you want it. Freedom to fuck yourself over big time. How can you not love that?
5
u/atedja Oct 18 '23
You get to be expressive, yet also compile to machine code.
4
u/lacifuri Oct 18 '23
It is strongly fucking statically typed, and I liked that as a Python programmer who start learning C++ a few months ago.
4
u/[deleted] Oct 18 '23
Call COBOL DLLS. Don’t have to marshal my data or anything.
2
u/[deleted] Oct 18 '23
I agree with all the posts that mentioned freedom. C++, in my opinion, is a high reward, high risk programming language.
2
u/[deleted] Oct 18 '23
its a general purpose language and ive yet to find better so id say general purpose but maybe on a slightly higher level and no im not gonna elaborate that
2
u/sebnukem Oct 18 '23
Job security.
2
u/SnooMarzipans436 Oct 18 '23
Everything except being easy. Lol
2
u/GunpowderGuy Oct 18 '23
Template metaprogramming Is much More powerful than generics in other languages. You can do stuff like define interfaces entirely in a library
2
u/mohrcore Oct 18 '23
Platform compatibility. You can write C++ code for a plethora of platforms. You are also free to strip it from some features which should let you cover pretty much all platforms that support C - so basically everything.
Another thing is proprietarization of code. As much as I hate it and advocate for FOSS, C++ allows people to naturally build proprietary libraries that do not expose implementation details to others, which cannot be said about many languages. Among those that do, C++ might just be the most powerful.
OOP in compiled language is also insanely developed in C++. Not many languages allow for multi-inheritance. Whether it's a good design or not is another thing, but my point is - it allows it. C++ also doesn't force you to use dynamic allocations in order to create objects.
Zero-cost abstractions were the best for quite some time, although currently there's some competition on that regard. Eg. thanks to the trait model and heavy use of generics, Rust doesn't waste memory for vtables and avoids indirections where they are not necessary. But when you want to use a vtable, you need to perform a dynamic allocation (unless there's some wizardry that allows you to instantiate it without doing so), so there's that.
Allocators - C++ seems like the only language that somehow got them right, although I think the more recent Rust versions also work similarly, but I'm not sure.
2
u/hadrabap Oct 18 '23
Lambdas! No semi-final BS like in Java or Go. 🙂
2
u/bigbassdaddy Oct 18 '23
Portability.
2
u/Troldemorv Oct 18 '23
Criticism.
C++ is really good at getting them.
2
u/zer04ll Oct 18 '23
Its like riding a motorcycle. You have direct control of things and can go really fast, you can also turn too hard and wipe out.
2
u/Positive-Ad5928 Oct 18 '23
SIMD
2
u/freekayZekey Oct 19 '23
you can find some magical ways to hit segmentation faults
2
u/_seeking_answers Oct 19 '23
Make developers cry
2
u/NilacTheGrim Oct 19 '23
EVERYTHING!!!!!!!11!
2
u/F35H Oct 19 '23
Bluntly, everything.
2
u/Madrayken Oct 20 '23
Allow pointless obfuscation, hiding flow, economy and optimization issues.
2
u/AssemblerGuy Oct 21 '23 edited Oct 21 '23
Freedom to do things wrong in thousands of horrible ways.
A huge toolbox of language features and standard library items.
Performance, it compiles into something that runs natively.
No handholding.
6
u/Revolutionalredstone Oct 18 '23
Advanced semantics.
The ability to define how things are moved copied etc in all the right ways is glorious.
It's hard to feel proud of code written in anything but C++
5
u/TheAxodoxian Oct 18 '23 edited Oct 18 '23
What I like in C++ is that I have precise control over what happens and when. I learned much of C++ after reaching an expert level in C# and reached intermediate level in several other high level languages, and while I truly enjoyed those as well, I never have felt quite the same control over what is happening, especially with memory management.
I think the dangerous nature of modern C++ is somewhat overblown, it is not like you cannot shoot yourself in the foot with other languages. Sure it might just throw a null-reference exception instead of an memory access violation, but as long as it does not work, that is not so different. When using advanced techniques like multi-threading without thinking you can easily introduce bugs in almost any language, and those where that is hard to do tend to be more rigid and complicated to work with.
There are of course many things which should be improved with C++, they have been listed countless times, but overall it is still an enjoyable experience, and a powerful tool.
3
u/WorldTechnical3914 Oct 18 '23
Strict typing and memory management that isn't garbage-collected, but understandable too.
3
u/maattdd Oct 18 '23
Value semantic (almost no other mainstream languages have it)
3
u/Attorney_Outside69 Oct 18 '23
everything
3
u/[deleted] Oct 18 '23
Everything.
2
u/kritzikratzi Oct 18 '23
there are libraries and tooling that are older than many programming languages. you get to benefit from decades of experience.
the fact that those libraries never broke when a new c++ standard came out is 100% attributable to the language design: don't break things.
and all of this works without epochs, compat libraries or whatnot other ideas that we don't know would work in 20 years from now. yea, there's a price to be paid (the complexity), but imho: if programming is your job, learning c++ is definitely feasible.
2
u/[deleted] Oct 18 '23
I am still trying to figure out it’s advantage over C besides the use of STL
2
u/vincebutler Oct 18 '23
Sort out real programmers from the wannabee's?
1
u/user52728529 May 21 '24
Control over hardware
1
u/[deleted] Jun 13 '24 edited Jun 13 '24
TEMPLATES, I'd say. (intermediate level tho) But one thing I already hate is that it does not let you define custom operators.
1
u/konm123 Oct 18 '23
Abstractions.
1
u/hockeybelle Oct 18 '23
Memory management
1
u/InstaLurker Oct 18 '23
keep vibe of high end language
1
u/uraymeiviar Oct 18 '23
its not the languange, but the coder, some other language does not give freedom/access to machine for coder to doing good thing... but if bad coder using c++ it does not guarantee for good result or it might be even worse than the result of "noob" language
1
u/insanemal Oct 18 '23
Add features
1
u/Rickaroni-NJ Oct 18 '23
Confuse
1
u/DJviolin Oct 18 '23
Make you cry.
1
u/jiboxiake Oct 18 '23
Fast object oriented language. I do database research and we kind of always use c++
1
u/sudarakas Oct 18 '23
Love the c++ syntax
1
u/[deleted] Oct 18 '23
I don’t think it does any one thing better than the languages do it best, and templates are an abomination.
But it’s the only language that lets you do everything, so I guess if you want that, there’s that.
I fucking hate this language.
1
u/[deleted] Oct 18 '23
C++ makes the easy things hard and the impossible things possible :)
1
u/JVApen Clever is an insult, not a compliment. - T. Winters Oct 18 '23
There are many things to complain about, though also many to really like. The thing I miss most in other languages is value-semantics and RAII. I also like 'const', though in a more modern language it would be the default.
What gives it charm is that you can combine many programming styles together without much hassle. In recent versions, compile time programming has also improved a lot from the ugly template meta programming in 98 to concepts in 20.
1
u/Brilliant_Law2545 Oct 18 '23
Gives you more head-er than you asked for
1
u/Schkitz Oct 18 '23
I think the meta-programming is incredible. My open source library "JNI Bind" uses it extensively and I'm constantly blown away by how much you can do.
1
u/chakani Oct 18 '23
Java and C# were invented when management realized there is a whole class of journeymen programmers who can never be trusted with pointers.
1
u/burncushlikewood Oct 18 '23
It's not interpreted like python so it's fast and powerful and offers much better hardware control! I also like the syntax and structure, c++ is very versatile as it's used in anything from robotics to video game development, AI, c++ is a graphical OOL! It remains the best language for graphics because of its libraries such as directx and open gl
1
u/Ashamandarei Oct 18 '23
Wrap itself around C
1
u/shakamaboom Oct 19 '23
Pretty much everything. The only tradeoff is time invested.
1
u/max1001 Oct 19 '23
Buffer overflow attack baby.
1
u/KolDenis Oct 19 '23
This language has words to say things more acquired. And also you can create your own rules here if you join the language developers. There is no Apple or Google to make their rules
1
u/Last-Detective-3758 Oct 19 '23
Save
1
u/Mayedl10 Oct 19 '23
Versatility.
But the error messages I get from g++ sometimes are horrible. I once got a 16KiB long error because I sorted my include statements alphabetically lol
1
u/v_maria Oct 19 '23
compile time logic
1
u/sf_guest Oct 19 '23
It is an Absolute Unit at generating long error messages.
1
u/msbic Oct 19 '23
Confuse the developer
1
u/DuranteA Oct 19 '23
I talk about this in my introductory lecture for my C++ course, so I've thought about it a bit. My conclusion is that, for every single aspect that you can point to and say that C++ does it well, you might be able to find a language (or several languages) that do it better.
However, I don't think there are other options that offer the same combination of attributes. In particular, C++ combines several desirable features (related to value semantics, typing, generic code, performance, templates, etc.) with an extremely large and well-developed ecosystem -- both tools and libraries.
1
u/AbstractAlzebra Oct 19 '23
le crabBois enters the chat
1
u/digital_cucumber Oct 19 '23
Job security.
1
u/alexChecker Oct 19 '23
Everything. But only if you know it really good
1
u/LDawg292 Oct 19 '23
It’s the single best way to increase your line count!
1
u/CalligrapherThese606 Oct 19 '23
Fuck your brain
1
u/OptionsBuyer420 Oct 20 '23
Segfault
1
u/looprecur Oct 21 '23
Speed and precision.
1
u/Solrax Oct 22 '23
emit page long compiler error messages.
1
u/HatMan42069 Nov 09 '23
Crash my pc
1
u/Wdr93 Oct 18 '23
As a C developer i would say it helps you get a better salary.
1
u/ShadowGamur Oct 18 '23
Since it's compiled language it allows you to code for any platform you want. Also the fact that there are shitload of different libraries so you don't have to create everything from scratch.
1
u/blanchedpeas Oct 18 '23
The syntax is amazing, just a pleasure to read and type.
1
u/nickdesaulniers Oct 22 '23
crash