Should C Style Be Used in C++?

ccoding-style

As I've been developing my position on how software should be developed at the company I work for, I've come to a certain conclusion that I'm not entirely sure of.

It seems to me that if you are programming in C++, you should not use C style anything if it can be helped and you don't absolutely need the performance improvement. This way people are kept from doing things like pointer arithmetic or creating resources with new without any RAII, etc. If this idea was enforced, seeing a char* would possibly be a thing of the past.

I'm wondering if this is a conclusion others have made? Or am I being too puritanical about this?

Best Answer

It is basically the way standard C++ is intended and encouraged (by the committee and the community) to be used:

  • use C++ language idioms (mostly based on RAII, like smart pointers)
  • don't use C language idioms until you can't avoid it (which still happen regularly, when interfacing with C interfaces)

This is what we have been calling "modern C++" for almost 10 years now. But most C++ developers start only now to realize it makes code looks like there is not much need for raw pointers, writing new/delete, and other error-prone constructs.

Now these constructs (C or not) are still there both for retrocompatibilty and for allowing you to write libraries to, again, free the other developers from having to play with them. Also, C should be used to interface with C libraries, for low level constructs that require C-style code. Any other case, you can avoid using C idioms when you have C++ available.

For clarification: using C style doesn't improve performance (assuming you understand C++ constructs and RAII). In fact, a lot of algorithms written in C++ are faster than the same in C, just because C++ give more info to the compiler to make him optimize in calling context (I'm thinking about template algorithms/types for example).

So performance is not necessarily a valid reason to use C idioms when you write C++.

Related Topic