Why you’re writing your C++ code wrong
C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off. — Bjarne Stroustrup, creator of C++.
What would your reaction be when the creator or the language himself says that C++ is a dangerous language? Well C++ is a dangerous language, unless you know what you’re doing with it. The language is powerful, no doubt but with great power comes great responsibility. Some people may rebuke me, banish me from society for this but — C++ isn’t an all purpose language. Unless, again, if you’re not into heavy AAA game dev, developing memory intensive applications or framework where each byte matters, OS kernels, programming embedded systems. For everything else, there are languages which are not only easy to use but also less likely to blow on your face.
So let’s get back to the title. Why you’re writing C++ wrong and just blowing things away.
Now who am I addressing? I’m assuming you’re a college or university student or some nihilist who just wants to die too soon. (Why else would you pick this language aye?)
Whoever you’re, you need to up your C++ game or you’re going to blow your whole lower body organs soon enough. (One by one or the wholesale — that’s a big question, I’ll leave it for some research).
So let’s see how you’re writing bad, destructive and polluted C++ and making living a mess for everybody else.
Still Writing C in C++? Why?
This is one of the primary reasons though, and the victims and culprits all belong to academic class; meaning — college students and also course instructors. Usually where I come from the transition of languages in the college curriculum is like this: C > C++/ Java > C++/ Java
So students learn C in one semester, then move to C++ in the next or after one semester of Java and when they go to C++, they find the language constructs awfully similar. Yes, they’re. Even C++ compilers compile C code with ease. So, why write C++, let’s just give it a .cpp extension and show the glory of C right? Nope. Just because C is allowed, doesn’t mean you’ve to. If C was enough, there wouldn’t have been any need of C++. C++ should be written like C++. Not like C. C++ compilers provide support for C for backward compatibility, not for you to use them everywhere. Have some decency man!
Let’s face your C in C++ sandwich blunders one by one.
Still using arrays? Whoah!
For the love of god and human rights, please stop! C++ provides you Array, Vector containers. Use them! I do prefer vector though. Now what is a vector? It’s a container in C++ STL (more on that later), but in easier terms it’s an array type that can have dynamic size, you
can clear it anytime and can hold any data type you specify.
Now, yes you can do that using malloc, calloc, new etc ways, bleed yourself and allocate all the memory by yourself, manage a thousand pointers and then yell back, why is my program leaking memory or not working as expected? Because you’re too intelligent for your own good. Use vectors. It’ll do everything for you. Look at the following snippet. How hard was it to use a vector to hold integers?
Now compare it to what you’ve been doing with arrays all these time. With arrays you need to mention a fixed size, you can’t clear it on the fly, can’t mere with another one and so on. With vectors you can all do that!
Now what are begin() and end()? These are iterators that let you go over a container like Vector. You should explore yourself. Bo Qian has some excellent tutorials on STL. His explanation on iterators is here:
Also check: http://www.cplusplus.com/reference/vector/
Still using malloc and calloc?
Get an upgrade, do yourself a favor and, use the new and delete operator in C++. Will make your life easier. Example below.
Does deleting pointers release the memory always?
Nope. They get inactive but remain like ghosts in your memory, until some other program claims that part of the memory. Creepy. So what you should do? Mark the pointer null after usage because C++, even after all these years of usage has no way of letting you check if the memory was released or not(unless you’re using profiling tools). Yeah that’s why I’ve trust issues.
Stop calling character arrays with null terminators as strings!
C++ has a string type in std namespace. Please, use that and stop calling glorified character arrays strings. It’s far better, and can use all the benefits of STL.
More on string? Go here: http://www.cplusplus.com/reference/string/
Sometimes you may have to use C header files in C++. When you do, don’t name them in C style like a maniac. All of them have elegant C++ names. How?
stdio.h got renamed to cstdio in C++. Use that. Not the C one. Same for other header files as well. omit the .h and add a “c” in front. EZ.
And with these we’re done with the first epidemic. Writing C in C++. Now let’s move on.
Generics or Templates?
For your info, C++ doesn’t have generics. It however compensates with class and function templates, which kind of do the same job but are not generic like in other languages.
How you should use them?
Well using them is easy. Look at the snippet below. Should give you some idea. The problem is not with the syntax. The problem is when you should use them. There’s no easy answer. It all depends on your needs. The popular approach that has been followed for years is —
- Either template a function
- Or Template the whole class
But bear in mind templating the whole class will have overhead issues. But it’s also true that you may need to do so. So, in cases where templating the whole classes isn’t necessary, avoid so.
Including header files in your class headers
Typical C++ class implementation gives you two files. A header file for definitions and a cpp file for implementations. Now suppose you need to use strings in your class. Include that just in your header file. No need to include it in every cpp file or subclass files. Why? every include you write gets compiled over and over again. Imagine how much duplicate code you added in your life.
Newer compilers support a preprocessor directive called pragma once that tells the compiler to avoid duplicates but, you may have to work with old legacy compilers. So bear that in mind.
It’s not a code related error. It’s more of a design error. So think over it.
Try using modern practices
If you’re learning how a certain algorithm works then don’t use the built in functions in algorithm header file. Write them from scratch. Else, for heavy projects just use the functions in algorithm. Follow Bo Qian’s videos again. (Link above in vector section).
This was added in C++11. So if you’re using older compilers like the ones that come with Code Blocks, the following code won’t compile but it’s good to use if you’re on good IDE’s like Visual Studio/ CLion/ Xcode and using a compiler that supports C++11 or above.
A better way of printing arrays or vectors?
Use the copy function. See the following example.
Lambdas and Auto types
Lambdas are a whole new thing. Added in C++11. Lambdas have a very special place in Computer Science. And functional programming is pretty much a good skill to acquire these days. I won’t go in depth on what lambdas are. I’d suggest knowing more about functional programming before diving into lambdas. Also since C++14, the compilers support auto type for variables. You can watch these for more information.
Why I didn’t use “using namespace std”
That statement means — “Dear compiler you can assume that I can use anything from the namespace called std”. It’s fine for smaller projects where you don’t have any namespaces of your own. However, when you’re doing bigger projects and start defining your namespaces, there will be name conflicts. For example: std has a copy function, you also wrote a copy function in your namespace. And you’re using both. Result? BOOM! That’s why, avoid writing it. (Completely fine for using in your lab codes and class work, just avoid for large projects).
Let’s wrap it up
Enough chatter. Let’s wrap it up. And let me reiterate, don’t touch C++ unless your life depends on it. And when you do, don’t make life miserable for you and others. Chiáo.