Why don't people indent C++ access specifiers/case statements? - c++

I often see stuff like this:
class SomeClass {
public:
void someMethod();
private:
int someMember;
};
This seems totally unnatural to me (the same applies to case-statements when using switch). I expected something like this, when I started using C++ (it's been a long time since then, but I am still wondering):
class SomeClass {
public:
void someMethod();
private:
int someMember;
};
Is there a funded reason to break (otherwise) consistent indentation rules?

Increasing indentation normally reflects entry to a new nested scope, whereas both access specifiers and switch case statements don't vary the scope (the same is true of labels generally). Access specifiers can be optional in that you may start implementing a class or struct and have all members only need the implied access (i.e. private and public respectively), but then the code evolves and you need to add a specifier for the non-implied-access members: is it really worth having to suddenly change the indentation on all members? Again, there's no nested scope, so I think that would be actively misleading.
If you work on fixed-width terminals and wrap your lines accordingly, reindenting's a pain. But, it is useful to have the access specifiers stand out from the members, which means putting them back to the left somewhere - either in line with the class keyword or part-way there.
Personally, I do this:
class X
{
public:
int member_function()
{
switch (expression)
{
case X:
return 6;
default:
{
int n = get_value() / 6;
return n * n;
}
}
}
private:
int member_variable_;
};
Why do I not indent code for each case further? I can't claim what I do is particularly logical, but factors include:
I don't want to deemphasise the general switch/case indentation, as visually communicating the extent of the switch is important to quickly understanding the code
I'm happy just to put the { and } around existing case code - more like a comment "hey, I need a scope" - rather than feeling compelling to indent everything further, which doesn't make much sense even to me but kind of feels right - I like having the code for each case line up
some compilers do warn if you introduce new variables inside a case statement without introducing a scope, even if there are no cases when the variable is later used potentially uninitialised
I'm an 80-column coder generally, with 4 space indents normally, so being inside a switch - and thus obviously a function - means remaining columns are valuable.
Same for class/struct:
I want to scan the left column and quickly find the end of the class, or easily count the small classes on screen or in a printout; access specifiers at exactly the same indentation level deemphasise the class keyword, but it does help to have them visually distinct from the members (if the class/struct is more than a few lines, I also add a blank line beforehand)
I don't want to change existing class/struct member indentation when I introduce a private or protected specifier
In conclusion: lots of small factors go into developing people's indentation preferences, and if you want to be a C++ programmer in a corporate environment - especially a contractor - you just have to go with the flow and be able to change your own style sometimes too (e.g. I'm stuck in camelCaseLand right now, with public member variables starting with an uppercase letter - yikes!). Don't sweat it - it's not worth it.

The access specifiers are really just labels (as in those used by goto). People generally don't indent labels, or outdent them one level with respect to the surrounding code. So I would say this is not inconsistent at all.
The Standard also uses this style for access specifiers. Example from Chapter 10, paragraph 2:
class Base {
public:
int a, b, c;
};

Imagine such a class definition:
class SomeClass {
void ImplicitlyPrivateMethod();
public:
void someMethod();
private:
int someMember;
};
With the style of indentation you propose, one would need to change this into
class SomeClass {
void ImplicitlyPrivateMethod();
public:
void someMethod();
private:
int someMember;
};
(which looks not so nice to many people, especially if the "implicit" section is long enough).
I personally prefer half-indentation of such specifiers:
class SomeClass {
void ImplicitlyPrivateMethod();
public:
void someMethod();
private:
int someMember;
};
But this is a matter of personal taste.

As with many other things, it is important not to mistake the rule with the purpose. The purpose of indentation is making code clearer and easier to read by providing an extra visual hint on what belongs where. Now, in the particular cases you mention, together with namespaces, in many cases the extra indentation does not help in readability. The cases in a switch can be understood as if-elses, where you would not add the extra indentation. The cases are block delimiters similar to the curly braces.
switch ( var ) {
case 1: // if ( var == 1 ) {
code;
case 2: // } else if ( var == 2 ) {
code;
}
At class level, access modifiers can be considered to be block delimiters at the same level that the class braces. Adding an extra level of indentation does not make the code clearer:
class test {
public:
void foo();
private:
int member;
};
The same way goes with namespaces, where some people avoid indenting the whole namespace level. In all three cases, there is no clear advantage in adding the extra indentation and if you abide to short code lines (80/100 characters) and big enough indentation levels (8 or even 4 characters) then there might be an advantage to not indenting.
Personally, I never indent case or accessor modifiers, in the case of namespaces, it depends... a namespace that covers the whole source file will most probably not be indented, while namespaces that only take part of the source file will be indented --the rationale is that in the former case it adds no actual value, while in the second it does.

Two possible reasons:
that's how Bjarne Stroustrup indents them in his books
most text editors indent them that way automatically

Because public and private are labels which don't introduce a new scope, I prefer not to give them any special indentation, thus:
class foo {
public:
void something();
void something_else();
private:
int top_secret;
};
This way, the consistent indentation rule is "indentation equals scope".

It's all about scoping and grouping of branches. If these are not affected, then do not add an indentation level.
Take for instance the following:
if( test == 1 ) {
action1( );
} else if( test == 2 ) {
action2( );
} else {
action3( );
}
Take note of the levels of the statement blocks. Now re-write it as a case statement with indented cases:
switch( test ) {
case 1:
action1( );
break;
case 2:
action2( );
break;
default:
action3( );
break;
}
This does the exact same functionally, yet the indentations don't match of my actions. And I think it is this inconsistency that finally made me change to dropping the extra spurious indentation. (Even though I don't mind the half-indenting proposed by others, mind you.)

There are very few access modifier lines per class, and most editors color modifiers differently from everything else. They stand out plenty on their own, so adding tabs is unnecessary.

As mentioned earlier (though argued for non-indented access modifiers), access modifiers form logical blocks. While these are at the same level as the class braces, they are special.
Thus it's useful to have indentation to clearly show where each block starts and ends.
I personally think it makes the code clearer. Others will dissagree.
This is a rather subjective question.

Most editors indent them automatically. For me, I leave them as they are in small classes or small files or short switch statements, but for long ones or a long file with many long switch statements I use more indentation for easier readability.
I sometimes do this which I feel is as old style:
Class CClass
{
CClass();
~CClass();
Public:
int a;
Private:
int b;
};
CClass::CClass
{
TODO code;
}
This sometimes makes it easier when a file may contain more than 20 or 50 functions, so you can easily spot the beginning of every function.

Related

C++: Global variable vs local variables. What to use?

Sometimes I wanna use globals but instead of it I use local variables. Let we have some Font class:
class Font {
public:
class Alignment {
public:
unsigned short currentAlignment;
unsigned short FONT_ALIGN_LEFT = 0;
unsigned short FONT_ALIGN_CENTER = 1;
unsigned short FONT_ALIGN_RIGHT = 2;
// etc....
};
Alignment alignment;
void setFontAlignment( unsigned short fontAlignment ) {
this->alignment.currentAlignment = fontAlignment;
}
};
To use this class we need to do something like that:
Font font;
font.setFontAlignment( font.alignment.FONT_ALIGN_CENTER );
// if we need to check currentAlignment we need to do:
if ( font.alignment.currentAlignment == font.alignment.FONT_ALIGN_CENTER ) {...} // looks a little bit awful :)
Or we have another approach to do this:
= Font.h =
#define FONT_ALIGN_LEFT 0
#define FONT_ALIGN_CENTER 1
#define FONT_ALIGN_RIGHT 2
// etc....
class Font {
public:
unsigned short currentAlignment;
void setFontAlignment( unsigned short fontAlignment ) {
this->currentAlignment = fontAlignment;
}
}
To use this:
#include "Font.h"
...
Font font;
font.setFontAlignment( FONT_ALIGN_CENTER );
if ( font.currentAlignment == FONT_ALIGN_CENTER ) {...} // looks a little bit better :)
Which one is better for memory optimizing and why? Which one do you prefer to use? Or maybe you know some better solutions?
Although there are always exceptions, I usually go by (among others :-) the following guidelines:
Avoid globals as much as possible. Confine to smallest applicable
scope (within reason).
Avoid second guessing the compiler, except for grossly obvious
situations.
Actually, a combination of them. But let's clarify something. You don't speak about any global variable in your question. A global variable is a variable defined in the global scope.
The primary reason of using object oriented programming is not its efficiency (as it is slower than purely procedural code), but its ability to model the world. So, when creating an oop design, you shouldn't care too much about the resourced (time, memory), but how good it models the world.
The second version is bad, because it introduces a lot of constants in the global scope, and you want to avoid that. Also, it does a very bad job at encapsulating the data (the user of your Font class shouldn't care about the values of the alignment).
The first version is better, but there are some problems. First, you need to think about the objects you should have? Do you actually need an Alignment object? You may need it, but in this particular example, I don't see why. So, you could make it model the world as it is, without introducing some artificial elements:
class Font {
public:
unsigned short currentAlignment;
void alignLeft() {
this->currentAlignment = 0;
}
void alignCenter() {
this->currentAlignment = 1;
}
void alignRight() {
this->currentAlignment = 2;
}
};
Now it is very easy to use. I don't have to keep in my global scope unnecessary constants. Now, the problem is what happens when the user reads the value of the currentAlignment? Of course, you don't want to use the constants, but you don't need to. It really depends on the world you're modelling. As this is a Font class, it should be the only one who really cares about the value of the alignment. If somebody else needs the value, you could have some methods like isCenter() that return true when the font is center-aligned. But also, I would consider making the currentAlignment private.

dumb data object holds all common values c++, is this correct

So I am new to c++ and I'm writing for a scientific application.
Data needs to be read in from a few input text files.
At the moment I am storing these input variables in an object. (lets call it inputObj).
Is it right that I have to pass this "inputObj" around all my objects now. It seems like it has just become a complicated version of global variables. So I think I may be missing the point of OOP.
I have created a g++ compilable small example of my program:
#include<iostream>
class InputObj{
// this is the class that gets all the data
public:
void getInputs() {
a = 1;
b = 2;
};
int a;
int b;
};
class ExtraSolver{
//some of the work may be done in here
public:
void doSomething(InputObj* io) {
eA = io->a;
eB = io->b;
int something2 = eA+eB;
std::cout<<something2<<std::endl;
};
private:
int eA;
int eB;
};
class MainSolver{
// I have most things happening from here
public:
void start() {
//get inputs;
inputObj_ = new InputObj();
inputObj_ -> getInputs();
myA = inputObj_->a;
myB = inputObj_->b;
//do some solve:
int something = myA*myB;
//do some extrasolve
extraSolver_ = new ExtraSolver();
extraSolver_ -> doSomething(inputObj_);
};
private:
InputObj* inputObj_;
ExtraSolver* extraSolver_;
int myA;
int myB;
};
int main() {
MainSolver mainSolver;
mainSolver.start();
}
Summary of question: A lot of my objects need to use the same variables. Is my implementation the correct way of achieving this.
Don't use classes when functions will do fine.
Don't use dynamic allocation using new when automatic storage will work fine.
Here's how you could write it:
#include<iostream>
struct inputs {
int a;
int b;
};
inputs getInputs() {
return { 1, 2 };
}
void doSomething(inputs i) {
int something2 = i.a + i.b;
std::cout << something2 << std::endl;
}
int main() {
//get inputs;
inputs my_inputs = getInputs();
//do some solve:
int something = my_inputs.a * my_inputs.b;
//do some extrasolve
doSomething(my_inputs);
}
I'll recommend reading a good book: The Definitive C++ Book Guide and List
my answer would be based off your comment
"Yea I still haven't got the feel for passing objects around to each other, when it is essentially global variables im looking for "
so this 'feel for passing object' will come with practice ^^, but i think it's important to remember some of the reasons why we have OO,
the goal (in it simplified version) is to modularise your code so as increase the reuse segment of code.
you can create several InputObj without redefining or reassignig them each time
another goal is data hiding by encapsulation,
sometimes we don't want a variable to get changed by another function, and we don't want to expose those variable globally to protect their internal state.
for instance, if a and b in your InputObj where global variable declared and initialized at the beginning of your code, can you be certain that there value doesn't get changed at any given time unless you want to ? for simple program yes.. but as your program scale so does the chances of your variable to get inadvertently changed (hence some random unexpected behavior)
also there if you want the initial state of a and b to be preserved , you will have to do it yourself ( more temp global variables? )
you get more control over the flow of your code by adding level abstractions with classes/inheritances/operation overriding/polymorphisms/Abtract and interface and a bunch of other concepts that makes our life easier to build complex architectures.
now while many consider global variable to be evil, i think they are good and useful when used properly... otherwise is the best way to shoot yourself in the foot.
I hope this helped a bit to clear out that uneasy feeling for passing out objects :)
Is using your approach good or not strongly depends on situation.
If you need some high speed calculation you can't provide incapsulation methods for your InputObj class, though they are recommended, because it will strongly reduce speed of calculation.
However there are two rules that your can follow to reduce bugs:
1) Carefully using 'const' keyword every time you really don't want your object to modify:
void doSomething(InputObj * io) -> void doSomething(const InputObj * io)
2) Moving every action related with initial state of the object(in your case, as far as I can guess, your InputObj is loaded from file and thus without this file loading is useless) to constructor:
Instead of:
InputObj() { }
void getInputs(String filename) {
//reading a,b from file
};
use:
InputObj(String filename) {
//reading a,b from file
};
You are right that this way you have implemented global variables, but I would call your approach structured, and not complicated, as you encapsulate your global values in an object. This will make your program more maintainable, as global values are not spread all over the place.
You can make this even nicer by implementing the global object as a singleton (http://en.wikipedia.org/wiki/Singleton_pattern) thus ensuring there is only one global object.
Further, access the object through a static member or function. That way you don't need to pass it around as a variable, but any part of your program can easily access it.
You should be aware that a global object like this will e.g. not work well in a multithreaded application, but I understand that this not the case.
You should also be aware that there is a lot of discussions if you should use a singleton for this kind of stuff or not. Search SO or the net for "C++ singleton vs. global static object"

C++ Member Variables

Consider the following class:
class A
{
A();
int number;
void setNumber(int number);
};
You could implement 'setNumber' in 3 ways:
Method 1: Use the 'this' pointer.
void A::setNumber(int number)
{
this->number = number;
}
Method 2: Use the scope resolution operator.
void A::setNumber(int number)
{
A::number = number;
}
Method 3: Instead, denote all member variables with 'm' or '_' (this is my preferred method).
void A::setNumber(int number)
{
mNumber = number;
}
Is this just personal preference, or is there a benefit to choosing a particular method?
This is mostly a personal preference, but let me share my perspective on the issue from inside a company where many small games are being made simultaneously (and so there are many coding styles being used around me).
This link has several good, related, answers: Why use prefixes on member variables in C++ classes
Your option 1:
void A::setNumber(int number)
{
this->number = number;
}
First off, many programmers tend to find this cumbersome, to continually type out the ' this-> '. Second, and more importantly, if any of your variables shares a name with a parameter or a local variable, a find-replace designed to say, change the name of 'number' might affect the member variables located in the find-replace scope as well.
Your option 2:
void A::setNumber(int number)
{
A::number = number;
}
The problem I've run into with this, is that in large classes, or classes with large functions (where you cannot see the function or the class is named unexpectedly), the formatting of A::(thing) looks very much like accessing a part of a namespace, and so can be misleading. The other issue is the same as #2 from the previous option, if your names are similar to any variables you're using there can be unexpected confusion sometimes.
Your option 3:
void A::setNumber(int number)
{
mNumber = number;
}
This is the best of those three presented options. By creating (and holding to!) a syntax that involves a clear and meaningful prefix, you not only create a unique name that a local (or global) variable won't share, but you make it immediately clear where that variable is declared, regardless of the context you find it in. I've seen it done both like this ' mVariable ' and like this 'm_variable' and it mostly depends upon if you prefer underscores to uppercase concatenation. In addition, if your style tends to add things like ' p 's on for pointers, or ' g 's on for globals, this style will mesh well and be expected by readers.
It is a matter of style, thus personal preference, or a preference of the team you are working with or the boss of the team you are working with.
Option 4:
void A::setNumber(int n)
{
number = n;
}
Why is the benefit of using the same name for a member and a parameter. No good can come of this. Sure, it's clear now, but when your methods get large, and the prototype doesn't fit in the screen anymore, and there's some other developer writing code, he may forget to qualify the member.
its all personal preference
but here is a good discussion on it at a high non language level
https://stackoverflow.com/questions/381098/what-naming-convention-do-you-use-for-member-variables
I would say the choice between Method 1 and Method 3 is a matter of personal or organizational style.
Method 2 is an inferior because Class::member typically denotes a static member variable, and thus would cause confusion if used to disambiguate between a parameter and member variable.
I am going to agree with Luchian by providing a better variant. The other examples you provide are too cumbersome or confusing.
Option 4:
void A::setNumber(int aNumber)
{
theNumber = aNumber;
}
This is part of the coding standard we use at my employer and it is very clear what you are describing. It is not Hungarian notation.

C++ getters and setters best style

in Java code convention is simple and obvious, in this style:
public:
int GetMyAge(){
return myAge;
}
void SetMyAge(int myAge){
this->myAge = myAge;
}
private:
int myAge;
(I know it's "again the same thing", but) I have read most of related questions on SO and I still don't know "the best one" and "the most official" way to do it in C++. It can't be just a matter of preferences, can it?
EDIT:
Seems like it can.
Best not to do it at all. Can your age actually be changed like that? Blindly providing getters and setters for all properties is a sign you have not designed your class properly.
The best style is the one that allows you and your team to make quality software that your clients continue to pay you for.
How does this style work for you and your team? Do you find it causes (or prevents) bugs? Do you find it easy to maintain the code? Do you bicker about the formatting?
Answer those questions and the answer to your question will arise out of them.
A simple answer: class names are capital in general in c++ (except for the std classes), methods are lower case, some frameworks like Qt prefer camelCase, however I prefer underscore_notation -- and so do the STL see eg. "auto_ptr".
Classes do not always have separate .h files, because here a .java file is split up into a .h header (for an entire package), and .cpp implementation files, one per class.
class TipicalCamelCase {
public:
/// mark the frequently used small functions inline in the class def.
inline int getMyAge() const;
void setMyAge(int myAge=5); // defaults go to the definition.
/// for efficiently setting more complex things.
void setMyStuff(const MyStuff& myStuff);
/// a tipical class-valued getter
/// (sometimes scoffed at since it can have memory leaks
/// if you dismiss the class but still use and don't copy MyStuff.)
const MyStuff& getMyStuff() const;
/// a safe getter, but forces copying-out MyStuff.
MyStuff getMyStuff() const;
private:
int myAge;
static const int zero=0; // allowed only in the new C++11 standard.
static const int one;
};
Some implementations/initializations (usually in separate TipicalCamelCase.cpp file):
const int TipicalCamelCase::one = 1;
int TipicalCamelCase::getMyAge() const{
return myAge;
}
void TipicalCamelCase::setMyAge(int myAge_){
myAge = myAge_;
}
Underscore style is the same but
int Tipical_camel_case::get_my_age() const
{
return my_age;
}
I prefer this as it looks cleaner both in the header and in the implementation files.
You can see that function headlines are lengthier than in java. Especially you'll see with templates (generics) 2 lines' header is typical, so it is worth to put them a bit more separated.
template<typename _Tp>
int Class_name::general_function(_Tp);
I think it should do as a style intro.
If you use inheritance, for the java-style working, mark every function except the constructors virtual so that the #overrides behave correctly.
What you have written in the above code is a correct syntax . If you are looking for a thumb rule, code your acccessor functions in such a way that they are set / get exactly the values .
EG :
void SetMyAge(int newAge)
{
if(newAge > 10 && newAge < 100)
_age = newAge ;
}
I would prefer to put the validation "newAge > 10 && newAge < 100" in a different function, IsValidAge ; even if the code is just one line. On the long run, small functions help in maintaining the code, and helps new developers to understand the code better.
void SetMyAge(int newAge)
{
if(IsValidAge() )
_age = newAge ;
}
However I would like to comment on this
void SetMyAge(int myAge){
this->myAge = myAge;
}
It is good practice to differentiate the nameing convention of the class varaiable to _myAge .
EDIT
I think the variable name was comprehended improperly .
myAge should be named _myAge .

What are your favorite C++ Coding Style idioms [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What are your favorite C++ coding style idioms? I'm asking about style or coding typography such as where you put curly braces, are there spaces after keywords, the size of indents, etc. This is opposed to best-practices or requirements such as always deleting arrays with delete[].
Here is an example of one of my favorites: In C++ Class initializers, we put the separators at the front of the line, rather than the back. This makes it easier to keep this up to date. It also means that source code control diffs between versions are cleaner.
TextFileProcessor::
TextFileProcessor( class ConstStringFinder& theConstStringFinder )
: TextFileProcessor_Base( theConstStringFinder )
, m_ThreadHandle ( NULL )
, m_startNLSearch ( 0 )
, m_endNLSearch ( 0 )
, m_LineEndGetIdx ( 0 )
, m_LineEndPutIdx ( 0 )
, m_LineEnds ( new const void*[ sc_LineEndSize ] )
{
;
}
RAII: Resource Acquisition Is Initialization
RAII may be the most important idiom. It is the idea that resources should be mapped to objects, so that their lifetimes are managed automatically according to the scope in which those objects are declared.
For example, if a file handle was declared on the stack, it should be implicitly closed once we return from the function (or loop, or whichever scope it was declared inside). If a dynamic memory allocation was allocated as a member of a class, it should be implicitly freed when that class instance is destroyed. And so on. Every kind of resource—memory allocations, file handles, database connections, sockets, and any other kind of resource that has to be acquired and released—should be wrapped inside such a RAII class, whose lifetime is determined by the scope in which it was declared.
One major advantage of this is that C++ guarantees that destructors are called when an object goes out of scope, regardless of how control is leaving that scope. Even if an exception is thrown, all local objects will go out of scope, and so their associated resources will get cleaned up.
void foo() {
std::fstream file("bar.txt"); // open a file "bar.txt"
if (rand() % 2) {
// if this exception is thrown, we leave the function, and so
// file's destructor is called, which closes the file handle.
throw std::exception();
}
// if the exception is not called, we leave the function normally, and so
// again, file's destructor is called, which closes the file handle.
}
Regardless of how we leave the function, and of what happens after the file is opened, we don't need to explicitly close the file, or handle exceptions (e.g. try-finally) within that function. Instead, the file gets cleaned up because it is tied to a local object that gets destroyed when it goes out of scope.
RAII is also less-commonly known as SBRM (Scope-Bound Resource Management).
See also:
ScopeGuard allows code to "automatically invoke an 'undo' operation .. in the event that an exception is thrown."
When creating enumerations, put them in a namespace so that you can access them with a meaningful name:
namespace EntityType {
enum Enum {
Ground = 0,
Human,
Aerial,
Total
};
}
void foo(EntityType::Enum entityType)
{
if (entityType == EntityType::Ground) {
/*code*/
}
}
EDIT: However, this technique has become obsolete in C++11. Scoped enumeration (declared with enum class or enum struct) should be used instead: it is more type-safe, concise, and flexible. With old-style enumerations the values are placed in the outer scope. With new-style enumeration they are placed within the scope of the enum class name.
Previous example rewritten using scoped enumeration (also known as strongly typed enumeration):
enum class EntityType {
Ground = 0,
Human,
Aerial,
Total
};
void foo(EntityType entityType)
{
if (entityType == EntityType::Ground) {
/*code*/
}
}
There are other significant benefits from using scoped enumerations: absence of implicit cast, possible forward declaration, and ability to use custom underlying type (not the default int).
Copy-swap
The copy-swap idiom provides exception-safe copying. It requires that a correct copy ctor and swap are implemented.
struct String {
String(String const& other);
String& operator=(String copy) { // passed by value
copy.swap(*this); // nothrow swap
return *this; // old resources now in copy, released in its dtor
}
void swap(String& other) throw() {
using std::swap; // enable ADL, defaulting to std::swap
swap(data_members, other.data_members);
}
private:
Various data_members;
};
void swap(String& a, String& b) { // provide non-member for ADL
a.swap(b);
}
You can also implement the swap method with ADL (Argument Dependent Lookup) directly.
This idiom is important because it handles self-assignment[1], makes the strong exception guarantee[2], and is often very easy to write.
[1] Even though self-assignment isn't handled as efficiently as possible, it's supposed to be rare, so if it never happens, this is actually faster.
[2] If any exception is thrown, the state of the object (*this) is not modified.
CRTP: Curiously Recurring Template Pattern
CRTP happens when you pass a class as a template parameter to its base class:
template<class Derived>
struct BaseCRTP {};
struct Example : BaseCRTP<Example> {};
Within the base class, it can get ahold of the derived instance, complete with the derived type, simply by casting (either static_cast or dynamic_cast work):
template<class Derived>
struct BaseCRTP {
void call_foo() {
Derived& self = *static_cast<Derived*>(this);
self.foo();
}
};
struct Example : BaseCRTP<Example> {
void foo() { cout << "foo()\n"; }
};
In effect, call_foo has been injected into the derived class with full access to the derived class's members.
Feel free to edit and add specific examples of use, possibly to other SO posts.
pImpl: Pointer-to-Implementation
The pImpl idiom is a very useful way to decouple the interface of a class from its implementation.
Normally, a class definition must contain member variables as well as methods, which may expose too much information. For example, a member variable may be of a type defined in a header that we don't wish to include everywhere.
The windows.h header is a prime example here. We may wish to wrap a HANDLE or another Win32 type inside a class, but we can't put a HANDLE in the class definition without having to include windows.h everywhere the class is used.
The solution then is to create a Private IMPLementation or Pointer-to-IMPLementation of the class, and let the public implementation store only a pointer to the private one, and forward all member methods.
For example:
class private_foo; // a forward declaration a pointer may be used
// foo.h
class foo {
public:
foo();
~foo();
void bar();
private:
private_foo* pImpl;
};
// foo.cpp
#include whichever header defines the types T and U
// define the private implementation class
class private_foo {
public:
void bar() { /*...*/ }
private:
T member1;
U member2;
};
// fill in the public interface function definitions:
foo::foo() : pImpl(new private_foo()) {}
foo::~foo() { delete pImpl; }
void foo::bar() { pImpl->bar(); }
The implementation of foo is now decoupled from its public interface, so that
it can use members and types from other headers without requiring these dependencies to be present when the class is used, and
the implementation can be modified without forcing a recompile of the code that uses the class.
Users of the class simply include the header, which contains nothing specific about the implementation of the class. All implementation details are contained inside foo.cpp.
I like lining up code/initializations in 'columns'... Proves very useful when editing with a 'column' mode capable editor and also seems to be a lot easier for me to read...
int myVar = 1; // comment 1
int myLongerVar = 200; // comment 2
MyStruct arrayOfMyStruct[] =
{
// Name, timeout, valid
{"A string", 1000, true }, // Comment 1
{"Another string", 2000, false }, // Comment 2
{"Yet another string", 11111000, false }, // Comment 3
{NULL, 5, true }, // Comment 4
};
In contrast, the same code not indented and formatted as above would appear... (A little harder to read to my eyes)
int myVar = 1; // comment 1
int myLongerVar = 200; // comment 2
MyStruct arrayOfMyStruct[] =
{
// Name, timeout, valid
{"A string", 1000, true},// Comment 1
{"Another string", 2000, false }, // Comment 2
{"Yet another string", 11111000,false}, // Comment 3
{NULL, 5, true }, // Comment 4
};
Public Top - Private Down
A seemingly small optimization, but ever since I switched to this convention, I have a way more fun time to grasp my classes, especially after I haven't looked at them for 42 years.
Having a consistent member visibility, going from points of frequent interest down to the boring stuff, is extremely helpful, especially when the code ought to be self-documenting.
(sidenote for qt-users: slots come before signals because they should be callable like non-slot member functions, and apart from their slottyness be indistinguishable from non-slots)
Public, protected, private
then Factory, ctor, dtor, copying, swapping
then the class' Interface
At the very last, in a seperate private: section, comes the data (ideally only an impl-pointer).
This rule also helps a ton if you have problems keeping your class declaration uncluttered.
class Widget : public Purple {
public:
// Factory methods.
Widget FromRadians (float);
Widget FromDegrees (float);
// Ctors, rule of three, swap
Widget();
Widget (Widget const&);
Widget &operator = (Widget const &);
void swap (Widget &) throw();
// Member methods.
float area() const;
// in case of qt {{
public slots:
void invalidateBlackHole();
signals:
void areaChanged (float);
// }}
protected:
// same as public, but for protected members
private:
// same as public, but for private members
private:
// data
float widgetness_;
bool isMale_;
};
In if statements, when there are difficult conditions, you can clearly show which level each condition is using indentation.
if ( ( (var1A == var2A)
|| (var1B == var2B))
&& ( (var1C == var2C)
|| (var1D == var2D)))
{
// do something
}
re: ididak
I fix code that breaks long statements into too many short lines.
Let's face it: it's not the 90's any more.
If your company can't afford widescreen LCDs for its coders, you need to get a better job :)
Compile-time polymorphism
(Also known as syntactic polymorphism and static polymorphism, contrast with runtime polymorphism.)
With template functions, one can write code that relies on type constructors and call signatures of families of parametrized types, without having to introduce a common base class.
In the book Elements of Programming, the authors refer to this treatment of types as abstract genera. With concepts one can specify the requirements on such type parameters, though C++ doesn't mandate such specifications.
Two simple examples:
#include <stdexcept>
template <typename T>
T twice(T n) {
return 2 * n;
}
InIt find(InIt f, InIt l,
typename std::iterator_traits<InIt>::reference v)
{
while (f != l && *f != v)
++f;
return f;
}
int main(int argc, char* argv[]) {
if (6 != twice(3))
throw std::logic_error("3 x 2 = 6");
int const nums[] = { 1, 2, 3 };
if (nums + 4 != find(nums, nums + 4, 42))
throw std::logic_error("42 should not have been found.");
return 0;
}
One can call twice with any regular type that has a binary * operator defined. Similarly, one can call find() with any types that are comparable and that model Input Iterator. One set of code operates similarly on different types, with no shared base classes in sight.
Of course, what's really going on here is that it's the same source code being expanded into various type-specific functions at template instantiation time, each with separate generated machine code. Accommodating the same set of types without templates would have required either 1) separate hand-written functions with specific signatures, or 2) runtime polymorphism through virtual functions.
No favorites but I will fix code that has:
tabs - causes misalignment in many IDEs and code review tools, because they don't always agree on tab at mod 8 spaces.
lines longer than 80 columns - let's face it, shorter lines are more readable. My brain can parse most coding conventions, as long as the lines are short.
lines with trailing whitespaces - git will complain about it as whitespace errors, which show up as red blobs in diffs, which is annoying.
Here is a one-liner to find the offending files:
git grep -I -E '<tab>|.{81,}| *$' | cut -f1 -d: | sort -u
where <tab> is the tab character (POSIX regexp doesn't do \t)
if/while/for parenthesized expression(s) WITH a space separator
if (expression) // preferred - if keyword sticks out more
vs.
if(expression) // looks too much like a void function call
I guess this implies that I like my function calls to NOT have a space separator
foo(parm1, parm2);
After working with someone who was partly blind - and at his request - I switched to using many more spaces. I didn't like it at the time, but now I prefer it. Off the top of my head, the only place where there isn't whitespace between identifiers and keywords and whatnot is after a function name and before the following parentheses.
void foo( int a, int b )
{
int c = a + ( a * ( a * b ) );
if ( c > 12 )
c += 9;
return foo( 2, c );
}
Template and Hook
This is a way to handle as much as possible in a framework and give a door or hook for customization by users of a framework. Also known as Hotspot and Template Method.
class Class {
void PrintInvoice(); // Called Template (boilerplate) which uses CalcRate()
virtual void CalcRate() = 0; // Called Hook
}
class SubClass : public Class {
virtual void CalcRate(); // Customized method
}
Described by Wolfgang Pree in his book Design Patterns for Object-Oriented Software Development.
I don't know if it qualifies as an idiom, exactly, but quite a bit of heavy-duty template programming depends (often heavily) on SFINAE (substitution failure is not an error). A couple of the answers to a previous question have examples.
I really like putting a small statement on the same line as an if
int myFunc(int x) {
if(x >20) return -1;
//do other stuff ....
}
Not sure if this counts as an idiom, but I tend to use doxygen-style inline comments even when the project isn't -yet- using doxygen...
bool MyObjects::isUpToSomething() ///< Is my object up to something
(aside. my comments are not usually quite that lame.)
It's useful to put function names on a new line, so you can grep like
grep -R '^fun_name' .
for them. I've seen that style used for a loads of GNU projects and like it:
static void
fun_name (int a, int b) {
/* ... */
}
Document the return values on the function line, so they are very easy to find.
int function(void) /* return 1 on success, 0 on failure */
{
return 1;
};
Write each method or function argument on a separate line such that it can be easily commented.
int ReturnMaxValue(
int* inputList, /* the list of integer values from which to get the maximum */
long size, /* count of the number of integer values in inputList */
char* extraArgs /* additional arguments that a caller can provide. */
)
I'd suggest PIMPL or as James Coplien originally called it "Handle Body".
This idiom allows you to completely decouple interface from implementation. When working on the rewrite and re-release of a major CORBA middleware component, this idiom was used to completely decouple the API from the implementation.
This practically eliminated any possibility reverse engineering.
An excellent resource for C++ idioms is James Coplien's excellent book "Advanced C++ Programming Styles and Idioms". Highly recommended!
Edit: As pointed out below by Neil, this book is quite out of date with many of his recommendations actually being incorporated into the C++ standard itself. However, I still find it to be a source of useful info, esp. in the form of his PLoP paper on C++ idioms where many idioms were recast into patterm form.
I always nitpick and edit the following:
Superfluous newlines
No newline at EOF
I usually stick to KNF described in *BSD STYLE(9)
I tend to put an else on all of my ifs.
if (condition)
{
complicated code goes here
}
else
{
/* This is a comment as to why the else path isn't significant */
}
Even though it annoys my coworkers.
You can tell at a glance, that I considered the else case during coding.