Ed Grochowski's Website

C++ Procedural Programming

Ed Grochowski

Written 12-22-2024

Introduction

This article describes the subset of the C++ language that I use in my programs. Written in procedural style, many of these programs predate object-oriented programming. I use the subset of the C++ language that is C and select C++ features:

  • Constructors, destructors, new, and delete
  • Namespaces
  • Reference parameters
  • bool and const
  • Templates

The advantages over plain C are as follows.


Constructors, destructors, new, and delete

Constructors and destructors perform initialization and tear-down at the time a struct is created and destroyed. This precludes bugs due to uninitialized members, never-free, double-free, and use-after-free. Constructors and destructors are especially valuable in libraries since the caller is no longer relied on to perform these functions.


Namespaces

C++ anonymous namespaces replace static declarations in C. This reduces visual clutter.

Named namespaces eliminate the need to create globally unique names. They are an easy way to avoid naming collisions.


Reference parameters

C passes parameters only by value, while C++ adds passing parameters by reference. For a parameter that must return a value, passing by reference hides taking an address in the caller and dereferencing a pointer in the callee. This again reduces clutter and makes the code easier to get right.


bool and const

Both are improved over their C counterparts. In particular, const has eliminated a major use of the C preprocessor.


Templates

Templates allow one to create similar functions that operate on different data types. This eliminates redundant function definitions that differ only in type.


Conclusion

If you are working on C programs, you may want to consider migrating to a subset of C++. The benefits easily outweigh the effort required.