DEV Community

Discussion on: Pitch me on C++

Collapse
 
scottmichaud profile image
Scott Michaud

If you like C#, imagine if the compiler automatically inserted "using" for you. You never needed to remember to write it. C++ does that.

Lots of C++ features are about letting developer hide complexity (almost always from the caller). When used correctly, the higher level ("business logic") code can use instances of types and safely assume that they are doing the right thing. You can then compose those solutions to build up the actual solution that you're trying to do, relying upon each component to do the right thing. (This is not possible in garbage collected languages because you never know when or if the garbage collector will run.)

For a concrete example, imagine that you are writing a program that records your screen while a window is up.

In other languages, you will need to remember to stop the recording, otherwise you will corrupt the file. There may be several ways that the window can close, so you will need to make sure that function is called in every possible control flow.

In C++: Make the handle to the video recorder a field of the window (NOT the memory address of the handle, but the actual handle itself). When the window gets destroyed, it will destroy all fields. If the person who wrote the video recorder made sure to stop any pending recordings when its handle is destroyed, then the compiler will automatically call stop. When the window instance is destroyed, the video recorder has no-where to live, so it is destroyed, and its destruction process safely stops the recording.

The caller didn't need to think about this, even if a (normal) error is encountered.

(Normal error meaning that your program is still in control of execution. It won't help you if the OS forcibly stops your execution, or you encounter a power failure, etc. Basically, if a "finally" would have helped you in another language, then you can rely upon C++ just doing the right thing without the caller needing to remember anything.)