After primarily working in C# for the last 5 years I recently switched back to c++ for a large project. I am going to use this article to post notes/gotcha’s/tips as a I come across them. I already have a few to add, and will update as I go along. Hopefully they help some c# programmers out there. They are listed in no particular order.
C++ does not support template type constraints/guards on template definitions
Gotcha: C++ does not support template type constraints/guards on template definitions. I ended up using static asserts (requires c++ 11), the example shown below uses helper methods from the popular boost library.
1 2 3 4 5
1 2 3 4 5 6
By default inheritance is private in c++
1 2 3 4
Don’t forget the “public” declaration if you are used to c#.
1 2 3 4 5
Member access specified at group level
Access identifier specified on each member.
Access can be grouped.
1 2 3
C++ supports multiple inheiritance
Unlike C#, C++ supports multiple inheiritance, while this may seem like a benifit it should be used very very rarely. If you find your object model requires multiple inheiritance it is best to reevaluate your design or you will end up facing issues like the diamond of death.
Rule of 3
Remember the rule of 3. If you require any of the following then you should explicitly define all three.
- copy constructor
- copy assingment operator
Temproraries with Parameterless Constructors
Don’t include parathesis on paramaterless constructors the compiler will favour resolving it as a function declaration and you will end up with an error message like:
error: request for member 'method' in 'someObj', which is of non-class type 'someType()'
STL containers copy their values.
When adding items to STL containters remember the container does a copy and keeps track of it’s own copy of the item being added.
Follow the Virtual Constructor Idiom
When creating abstract base classes follow the virtual constructor idiom and create virtual clone and create methods. This allows you to create collections of base types while still being able to copy them without knowing their concrete type.
Dynamic Linking Libraries
Here are some tips and tools for working with dynamically linked libraries and shared objects.
- Shared library files to be registered must start with “lib”
- Use ldconfig -v to see registered libraries
- Use ldconfig to reload linked libraries
- Export ldpath to temporarily point executable at your lib, handy for scripting.
- Use ldd command to view an executables dependencies.
- Use nm –demangle
to view shared objects exported symbol list.
- Use c++filt
to lookup runtime symbol lookup errors.