Private, Public, Const, and Static

When using C++ for object-oriented programming, there are some basic concepts and best practices that should be followed for good software engineering. First is the use of public and private in class definitions. Most programmers moving from C to C++ are accustomed to using structs, where all fields are "public" for others to access; in C++, all fields in a class are "private" by default instead. There is a good reason for this: everything in a class should be private unless otherwise necessary. If there is some data that you wish to "expose", you are best off using getter/setter methods to do so rather than making the data public. If some other class needs direct access to the data, make it a "friend" class instead of making the data public. Be smart about which methods are made public as well, and limit the amount of exposure to the "internal workings" of your class.

Next is the use of "const", which stands for "constant"; this keyword signifies data that will not be changed. Whenever you are passing a data structure into a function (whether by pointer or by reference), you should make a decision as to whether that function should be allowed to modify that data; if not, then you should make that argument const. When you are returning a data structure from a function, you should make the same determination and make it const if it should not be altered by the caller. Whenever you are declaring a variable or data structure that should remain unchanged by the code that uses it, you should mark it as const. Doing this ensures the integrity of your data, and which leads to cleaner and more "secure" software. It will also help to detect potential problems in your code at compile-time, which saves time and trouble with testing. Note that these best practices apply to C programming as well. For C++, const can also be used with class methods, when a class method does not alter the contents of the class (as would typically be true for "getter" methods, but not "setter" methods).

When you want to have a single instance of a data structure, you should use the "static" keyword. For example, if you have a class that has a single global instance, you can declare that instance as a "static" member of the class, and then callers who request that single instance can use that static member from the class. You can even declare local variables as "static" to use a single instance of the data structure rather than having it allocated on every invocation of the code. It is common for global variables and structures to be declared as "static" (and also as "const" if they are to remain unchanged).

The proper use of these keywords to define the access privileges to your data will not only make your code and classes more secure and more portable, but also easier to change and add improvements without affecting those dependent on your code.

if (isMyPost) { }